Inherit from abstract class with properties of another type (.NET 3.5, C#)
I have 3 following classes:
public class BaseProperty1{
public string Property1 {get; set;}
}
public class ChildProperty1 : BaseProperty1 {
}
public abstract class Base{
public abstract BaseProperty1 bp1 {get; set;}
}
I'm trying to derive a following class from Base:
public class Child : Base{
public ChildProperty1 bp1 {get; set;}
}
But I'm getting an error that "set" and "get" methods are not implemented. Is it just the 开发者_高级运维syntax I'm using or my way of thinking is wrong?
Thank you!
You won't be able to use Auto Properties since you have to match the type of the base class exactly. You'll have to go the old fashioned way:
public abstract class Child : Base
{
private ChildProperty1 _bp1;
public BaseProperty1 bp1
{
get { return _bp1; }
// Setter will be tricky. This implementation will default to null
// if the cast is bad.
set { _pb1 = value as ChildProperty1; }
}
}
You might also be able to use generics to solve the problem:
public abstract class Parent<TProp> where TProp : BaseProperty1
{
public abstract T bp1 { get; set; }
}
public abstract class Child : Parent<ChildProperty1>
{
public ChildProperty1 bp1 { get; set; }
}
If you mark method or property as an abstract, you must implement it in inherited class. You can hide old property (bp1 in Base class) and write new one with another return type like this:
public abstract class Base{
public BaseProperty1 bp1 {get; set;} //without abstract identifier
}
public class Child : Base
{
public new ChildProperty1 bp1 { get; set; } // with new modifier
}
精彩评论