gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:39 25 4
gpt4 key购买 nike

我有任意数量的继承 classToBeInherited 的类,classThatInheritsanotherClassThatInherits 等。然后我有一个方法 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; }
}

然后在 classThatInheritsanotherClassThatInherits 中使用 public override int myValue { get;放; } 来实现该属性。

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

关于c# - 从继承另一个的类中获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com