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

时间:2015-12-31 05:08:53

标签: c# inheritance

我有一定数量的类,classThatInheritsanotherClassThatInherits等继承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
        //***
    }
}

2 个答案:

答案 0 :(得分:3)

myValue移至classToBeInherited

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

然后在classThatInheritsanotherClassThatInherits中使用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);