C# 我可以´;无法访问多态列表中的公共函数
我在Unity3D有以下课程:C# 我可以´;无法访问多态列表中的公共函数,c#,list,inheritance,polymorphism,C#,List,Inheritance,Polymorphism,我在Unity3D有以下课程: public abstract class Property{ public abstract bool equals (int value); } 还有一位继承者: public class A : Property{ int currentValue; // Constructor public A(int newValue){ currentValue = newValue; } // G
public abstract class Property{
public abstract bool equals (int value);
}
还有一位继承者:
public class A : Property{
int currentValue;
// Constructor
public A(int newValue){
currentValue = newValue;
}
// Getter
public int getCurrentValue(){
return currentValue;
}
public override bool equals (int value){
// Do something
}
}
还有一类B等于A
在主要功能中,我有:
List<Property> list = new List<Property> ();
list .Add (new A (0));
list .Add (new B (2));
Debug.Log (list [0]); // Prints "A" -> It´s OK
Debug.Log (list [1]); // Prints "B" -> It´s OK
List List=新列表();
列表。添加(新的A(0));
增加(新的B(2));
Debug.Log(列表[0]);//打印“A”->没问题
Debug.Log(列表[1]);//打印“B”->没问题
但是我想打印对象A的当前值,我不明白为什么如果我执行
Debug.Log(列表[0].getCurrentValue())
,我就无法访问该函数!但这是公开的!出了什么问题?您的列表是属性
实例的通用列表。因此编译器只知道列表
(在本例中为A
和B
)的元素属于属性类型
因为抽象属性
类没有调用
getCurrentValue()
编译器将显示您看到的错误。它根本不知道元素实际上是A
类型,因此它具有该方法
如果A
和B
都有getCurrentValue
方法(并且只有Property
的每个子类都应该有该方法),您还应该将其添加到Property
类中:
public abstract class Property{
public abstract bool equals (int value);
public abstract int getCurrentValue();
}
将对象强制转换为其类型:
Debug.Log((list[0] as A).getCurrentValue());
或者更清楚地说:
A a = (A)list[0];
Debug.Log(a.getCurrentValue());
您的列表包含属性类型的元素
:
List<Property>
虽然Property
的任何给定实现都可能有其他方法,但也可能没有。编译器不能保证这一点
如果该方法需要用于所有属性
对象,请将其添加到属性
类:
public abstract class Property{
public abstract bool equals (int value);
public abstract int getCurrentValue();
}
并在派生类中重写它:
public override int getCurrentValue(){
return currentValue;
}
然后可以对列表中的任何元素调用getCurrentValue()
。因为列表包含Property
类型,并且Property
上只有一个方法-equals
您忘记了第二个示例中的强制转换A=(A)list[0]代码>谢谢!我想,当我在列表中添加一个新的a(0)
时,我就可以使用该方法了。
public override int getCurrentValue(){
return currentValue;
}