从继承另一个类的类中获取一个变量

本文关键字:一个 变量 获取 继承 另一个 | 更新日期: 2023-09-27 18:28:31

我有任意数量的继承classToBeInherited的类,classThatInheritsanotherClassThatInherits等。然后我有一个方法b,它需要能够从继承classToBeInherited的类访问myValue。没有铸造,我怎么能做到这一点?

//This class will be inherited by other classes
public class classToBeInherited {
    public bool isSomething { get; set; }
}
//This class with inherit 'classToBeInherited'
public class classThatInherits : classToBeInherited {
    public int myValue { get; set; } //this needs to be accessable...
}
//...And so will this class
public class anotherClassThatInherits : classToBeInherited {
    public int myValue { get; set; }
}
private class normalClass {
    private void a() {
        classThatInherits cti = new classThatInherits();
        b(cti);
        anotherClassThatInherits acti = new anotherClassThatInherits();
        b(acti);
    }
    private void b(classToBeInherited c) {
        //***
        //get myValue from the classes that inherit classToBeInherited
        //***
    }
}

从继承另一个类的类中获取一个变量

myValue移动到classToBeInherited:

public class classToBeInherited {
    public bool isSomething { get; set; }
    public abstract int myValue { get; set; }
}

然后在classThatInheritsanotherClassThatInherits中使用public override int myValue { get; set; }来实现该属性。

此外,如果仅在某些类中需要myValue,则可以使用virtual而不是abstract属性。

var a = c as anotherClassThatInherits;
if (a != null)
{
    var myValue = a.myValue;
}

我不知道你为什么不想进行强制转换,但有上面这样的代码是很常见的。


更新

如果你真的不想选角,你可以使用reflection(但你仍然需要知道anotherClassThatInherits的类型)

var getter = typeof(anotherClassThatInherits).GetProperty("myValue").GetGetMethod();
var myValue = getter.Invoke(c,  null);