从继承另一个类的类中获取一个变量
本文关键字:一个 变量 获取 继承 另一个 | 更新日期: 2023-09-27 18:28:31
我有任意数量的继承classToBeInherited
的类,classThatInherits
、anotherClassThatInherits
等。然后我有一个方法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; }
}
然后在classThatInherits
和anotherClassThatInherits
中使用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);