C# 我可以´;无法访问多态列表中的公共函数

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

我在Unity3D有以下课程:

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;
}