Inheritance: derived properties in derived class
I am trying to figure out the best way to handle a derived class that also has a property in it that I want to also be derived from a different class. Let me show you the simplified classes:
public abstract class AttendanceEvent
{
public int Id { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
public AttendanceCode AttendanceCode { get; set; }
}
public abstract class AttendanceCode
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public AttendanceType Type { get; set; }
}
Now what I'd like to do is be able to have:
public class PublicAttendance开发者_开发问答Code : AttendanceCode {}
public class PublicLeave : AttendanceEvent
{
// PublicAttendanceCode takes the place of AttendanceCode
public PublicAttendanceCode AttendanceCode { get; set; }
}
And:
public class PrivateAttendanceCode : AttendanceCode {}
public class PrivateLeave : AttendanceEvent
{
// PrivateAttendanceCode takes the place of AttendanceCode
public PrivateAttendanceCode AttendanceCode { get; set; }
}
I thought about using Generics so I would have:
public abstract AttendanceEvent<T> where T : AttendanceCode
But I'm not sure if that is recommended for entities or if it would work with EF Code First. The other way I though about going about constraining the AttendanceCode is to constrain it in the constructor like so:
public class PublicLeave : AttendanceEvent
{
public PubliLeave(PublicAttendanceCode code, DateTime startDateTime, DateTime endDateTime)
{
//more code here
}
}
I'm wondering what is the recommended way of dealing with this type of situation and do you see any pitfalls with using one approach or the other?
Theres no conflict with your design. Each concrete implementation of AttendanceEvent
contains exactly one concrete implemenation of AttendanceCode
. PublicLeave
always w/ PublicAttendanceCode
and PrivateLeave
always w/ PrivateAttendanceCode
Just write your function bodies appropriately and everything will be fine.
Whenever you instantiate or pass in an AttendanceCode
for PublicLeave
make sure it is a PublicAttendanceCode
. Likewise, whenever you instantiate or pass in an AttendanceCode
for PublicLeave
make sure it is a PrivateAttendanceCode
Your constructor example looks just fine. In the body of it, but something like
public PubliLeave(PublicAttendanceCode code, DateTime startDateTime, DateTime endDateTime)
{
AttendanceCode = code;
StartDateTime = startDateTime; EndDateTime = endDateTime;
}
The only thing I would suggest is that you change some names, too many of them look alike. (ex - make the arguments to above constructor sDateTimeIn, eDateTimeIn
or somethin, and name the AttendanceCode
member something like myCode
instead of having it identical to the class's name)
精彩评论