简体   繁体   English

在派生类中,如何从基类的属性类型中获取派生类型的属性?

[英]In a derived class, how to have a property of a derived type from the type of the property in the base class?

This is a huge design problem that I often encounter and I think it is because I don't understand OOP right. 这是我经常遇到的巨大设计问题,我认为这是因为我对OOP的理解不正确。

Here is the class of the base Property : 这是基本Property的类:

public class BasePropety {}

Here is the type of my DerivedProperty: 这是我的DerivedProperty的类型:

public class DerivedProperty : BaseProperty
{
    public AClass A { get; set; }
}

Here is my base class : 这是我的基类:

public class BaseClass
{
    public BaseProperty Property { get; set; }
}

Here my derived class : 这是我的派生类:

public class DerivedClass : BaseClass
{
    public DerivedProperty Property { get; set; }

    public void MethodExample()
    {
        AClass aValue = this.Property.A;
    }
}

I could of course typecast my property but it is annoying: 我当然可以打字我的财产,但这很烦人:

public class DerivedClass : BaseClass
{
    public void MethodExample()
    {
        var typedProperty = (DerivedProperty) this.Property;
        AClass aValue = typedProperty.A;
    }
}

I know I can use the new keyword but I read here and there that it is a bad practice, so how I am suppose to achieve this ? 我知道我可以使用new关键字,但是我在这里和那里读到这是一个不好的做法,那么我应该如何实现呢? Should I create a new property ? 我应该创建一个新财产吗?

Thanks in advance for your answers. 预先感谢您的回答。

Sounds like you need generics instead: 听起来您需要泛型:

public class BaseClass<T> where T : BaseProperty
{
    public T Property { get; set; }
}

public class DerivedClass : BaseClass<DerivedProperty>
{
    public void MethodExample()
    {
        AClass aValue = Property.A;
    }
}

Note that this means there's only one property - whereas in your current code, you actually have two independent properties, which happen to have the same name. 请注意,这意味着只有一个属性-而在当前代码中,实际上您有两个独立的属性,它们恰好具有相同的名称。 I suspect you don't want that. 怀疑你不想那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM