开发者

Inherit from abstract class with properties of another type (.NET 3.5, C#)

开发者 https://www.devze.com 2023-03-07 00:30 出处:网络
I have 3 following classes: public class BaseProperty1{ public string Property1 {get; set;} } public class ChildProperty1 : BaseProperty1 {

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号