通用方法和类型转换

时间:2016-10-01 12:10:12

标签: c# generics generic-method

我阅读了以下问题(我会以与给定答案相同的方式解决):Passing derived type as argument to abstract class

但为什么它无法从派生类中找到value属性?即使我添加一个类型转换,也是不可能的:

public abstract class baseClass
{
    public abstract float function<T>(T a, T b) where T:baseClass;
}

public class derived: baseClass
{
    public override float function<derived>(derived a, derived b)
    {
        // Here value is not found
        return a.value + b.value;
    }

    public float value;
}

使用类型转换的示例也不起作用(并显示了建议冗余类型转换):

public abstract class baseClass
{
    public abstract float function<T>(T a, T b) where T:baseClass;
}

public class derived: baseClass
{
    public override float function<derived>(derived a, derived b)
    {
        // Here value is not found even with type cast
        return ((derived)a).value + ((derived)b).value;
    }

    public float value;
}

1 个答案:

答案 0 :(得分:2)

因为您在方法上声明了泛型类型参数。编译器不理解这应该是derived类型。它只知道你引入了一个新的通用类型参数。

你想要的是F-bound polymorphism,其中type参数是实现类,递归定义:

public abstract class BaseClass<T> where T : BaseClass<T>
{
    public abstract float Function(T a, T b);
}

public class Derived : BaseClass<Derived>
{
    public override float Function(Derived a, Derived b)
    {
        return a.Value + b.Value;
    }

    public float Value { get; set; }
}