C# inheritance issue
I'm using an API tha开发者_C百科t has a "Member" class. I wish to extend this so i have create "MemberProfile" which inherits from "Member"
I have some issue creating the constructor for this class. I wish to something like the following
var member = Member.GetCurrentMember();
var memberProfile = new MemberProfile(member);
How would the constructor on MemberProfile look. Do i need to do some kind of cast?
I suggest adding a Member
field to the MemberProfile
class and initialize it in the constructor. Don't inherit from Member
.
public class MemberProfile {
public Member Member { get; private set; }
public MemberProfile(Member member) { Member = member; }
}
If you really want to inherit from Member
, you'll have to copy all the properties off the passed argument to the new instance manually.
Mehrdad is correct; MemberProfile should not inherit from Member.
Making some assumptions about your application context, it seems likely that it is entirely plausible that at some point in the future one Member may have more than one Profile.
MemberProfile <<--uses--> Member
and not
MemberProfile --is-a--> Member
Use the decorator pattern
You would need to create a constructor which takes a Member as an argument and does a deep copy of the parameters.
public class MemberProfile : Member
{
public MemberProfile(Member member)
{
base.field1 = member.field1;
base.field2 = member.field2;
.
.
base.fieldn = member.fieldn;
}
}
精彩评论