通用方法和类型转换
Generic methods and type casting
我阅读了以下问题(我将按照给定答案的相同方式解决):
但为什么无法从派生的 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;
}
因为您要在方法上声明泛型类型参数。编译器不理解这应该是 derived
类型。它只知道您引入了一个新的泛型类型参数。
你想要的叫做F-bound polymorphism,其中类型参数是实现class,递归定义:
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; }
}
我阅读了以下问题(我将按照给定答案的相同方式解决):
但为什么无法从派生的 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;
}
因为您要在方法上声明泛型类型参数。编译器不理解这应该是 derived
类型。它只知道您引入了一个新的泛型类型参数。
你想要的叫做F-bound polymorphism,其中类型参数是实现class,递归定义:
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; }
}