我有一定数量的类,classThatInherits
,anotherClassThatInherits
等继承classToBeInherited
。
然后我有一个方法b
,它需要能够从继承myValue
的类中访问classToBeInherited
。如何在不进行投射的情况下实现这一目标?
//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
//***
}
}
答案 0 :(得分:3)
将myValue
移至classToBeInherited
:
public class classToBeInherited {
public bool isSomething { get; set; }
public abstract int myValue { get; set; }
}
然后在classThatInherits
和anotherClassThatInherits
中使用public override int myValue { get; set; }
来实现该属性。
Ofcorse,如果只在某些类中需要myValue
,那么您可以拥有virtual
而不是abstract
属性。
答案 1 :(得分:0)
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);