我遇到过一种情况,答案应该非常直截了当,但它让我望而却步。
public class Note
{
#region Properties
public int Id { get; set; }
public int ClientId { get; set; }
public int CandidateId { get; set; }
public int TypeId { get; set; }
public DateTime DateCreated { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
public string Message { get; set; }
#endregion
#region Methods
public void Save()
{
}
#endregion
}
public class History : Note
{
}
如您所见,History 继承了 Note。它们完全相同,两者之间的唯一区别是类型 Id。
从数据库获取数据时我有这个功能
public static Note Parse(SqlDataReader dr)
{
int TypeId = Convert.ToInt32(dr["TypeId"]);
Note Note;
if (TypeId == 1)
Note = new Note();
else
Note = new History();
Note.Id = Convert.ToInt32(dr["Id"]);
Note.TypeId = TypeId;
if (dr["ClientId"] != DBNull.Value) Note.ClientId = Convert.ToInt32(dr["ClientId"]);
if (dr["CandidateId"] != DBNull.Value) Note.CandidateId = Convert.ToInt32(dr["CandidateId"]);
Note.DateCreated = Convert.ToDateTime(dr["DateCreated"]);
Note.UserId = Convert.ToString(dr["UserId"]);
Note.UserName = Convert.ToString(dr["UserName"]);
Note.Message = Convert.ToString(dr["Message"]);
return Note;
}
然后在我的 MVC 页面上我有这个:
<ol id="interview-comments">
@foreach (Note Note in Model.Notes().OfType<Note>())
{
}
</ol>
<ol id="history-comments">
@foreach (History Note in Model.Notes().OfType<History>())
{
}
</ol>
我的问题很简单。这是正确的方法吗?
/r3plica