我有类任意金额,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
//***
}
}
移动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
属性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句