正在阅读:掌握 ASP.NET 之路:自定义实体类简介掌握 ASP.NET 之路:自定义实体类简介

2005-06-23 10:16 出处: 作者:Karl Seguin 责任编辑:moningfeng

对于在许多数据绑定控件提供的 OnItemDataBound 或 OnItemCreated 中执行处理的人来说,您可能会将 e.Item.DataItem 强制转换成 DataRowView。当绑定到自定义集合时,e.Item.DataItem 则被强制转换成自定义实体,在我们的示例中为 User 类:

'Visual Basic .NET
Protected Sub r_ItemDataBound (s As Object, e As RepeaterItemEventArgs)
Dim type As ListItemType = e.Item.ItemType
If type = ListItemType.AlternatingItem OrElse
? type = ListItemType.Item Then
Dim u As Label = CType(e.Item.FindControl("userName"), Label)
Dim currentUser As User = CType(e.Item.DataItem, User)
If Not PasswordUtility.PasswordIsSecure(currentUser.Password) Then
ul.ForeColor = Drawing.Color.Red
End If
End If
End Sub

//C#
protected void r_ItemDataBound(object sender, RepeaterItemEventArgs e) {
ListItemType type = e.Item.ItemType;
if (type == ListItemType.AlternatingItem ||
? type == ListItemType.Item){
Label ul = (Label)e.Item.FindControl("userName");
User currentUser = (User)e.Item.DataItem;
if (!PasswordUtility.PasswordIsSecure(currentUser.Password)){
ul.ForeColor = Color.Red;
}
}
}




管理关系
即使在最简单的系统中,实体之间也存在关系。对于关系数据库,可以通过外键维护关系;而使用对象时,关系只是对另一个对象的引用。例如,根据我们前面的示例,User 对象完全可以具有一个 Role:

'Visual Basic .NET
Public Class User
Private _role As Role
Public Property Role() As Role
Get
Return _role
End Get
Set(ByVal Value As Role)
_role = Value
End Set
End Property
End Class

//C#
public class User {
private Role role;
public Role Role {
get {return role;}
set {role = value;}
}
}



或者一个 Role 集合:

'Visual Basic .NET
Public Class User
Private _roles As RoleCollection
Public ReadOnly Property Roles() As RoleCollection
Get
If _roles Is Nothing Then
_roles = New RoleCollection
End If
Return _roles
End Get
End Property
End Class

//C#
public class User {
private RoleCollection roles;
public RoleCollection Roles {
get {
if (roles == null){
roles = new RoleCollection();
}
return roles;
}
}
}



在这两个示例中,我们有一个虚构的 Role 类或 RoleCollection 类,它们就是类似于 User 和 UserCollection 类的其他自定义实体或集合类。
键盘也能翻页,试试“← →”键

关注我们

最新资讯离线随时看 聊天吐槽赢奖品