Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从继承另一个类的类中获取变量_C#_Inheritance - Fatal编程技术网

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

C# 从继承另一个类的类中获取变量,c#,inheritance,C#,Inheritance,我有任意数量的类,继承的类,另一个继承的类,等等,这些类继承了类而不被继承。 然后我有一个方法,b,它需要能够从继承classToBeInherited的类访问myValue。我如何才能做到这一点,没有铸造 //This class will be inherited by other classes public class classToBeInherited { public bool isSomething { get; set; } } //This class with i

我有任意数量的类,
继承的类
另一个继承的类
,等等,这些类继承了
类而不被继承
。 然后我有一个方法,
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; }
}
然后在继承的
类和另一个继承的
类中,使用
public override int myValue{get;set;}
实现该属性


当然,如果只有一些类需要
myValue
,那么您可以使用
virtual
而不是
abstract
属性。

不,这对我不起作用。void b不需要知道继承的类。@bwoogie:我不认为这会使
void b不需要知道继承的类,但是如果你想避免强制转换,你可以使用反射。出于好奇,请查看我的最新答案。是否有原因使myValue不能成为要被继承的类的成员?由于函数b()需要一个类类型的参数被写入,所以myValue似乎应该是该类型的一部分。任何继承的类都可以访问父类的公共属性。所以我也认为你要做的是在类中声明我的值。有没有不这样做的功能限制?如果不是的话,你必须有演员才能完成。非常感谢你!将其设置为抽象正是我所需要的。
var getter = typeof(anotherClassThatInherits).GetProperty("myValue").GetGetMethod();
var myValue = getter.Invoke(c,  null);
public class classToBeInherited {
    public bool isSomething { get; set; }
    public abstract int myValue { get; set; }
}