Tim*_*ang 1 c# oop generics casting
public class P { }
public class B : P { }
public class A : P { }
public interface Interface<T> where T : P { }
public class IA : Interface<A> { }
public class IB : Interface<B> { }
public class Test
{
public void WhatTheFuck()
{
Interface<P> p;
p = new IA();// cast error here
p = new IB();// cast error here
//... somthing about interface<p>
}
}
Run Code Online (Sandbox Code Playgroud)
得到这个错误:
严重性代码描述项目文件行抑制状态错误 CS0266 无法将类型“AssUploaderSystem.IA”隐式转换为“AssUploaderSystem.Interface”
我想制定一个通用的解决方案,因为 A 类和 B 类也是 P 类实现的。
所以我只想写一次,但我不能投射到某个类。我能怎么做 ?
您可以将接口中的泛型类型参数声明为协变或逆变。协方差允许接口方法具有比泛型类型参数定义的更多的派生返回类型。逆变允许接口方法具有比泛型参数指定的更少派生的参数类型。具有协变或逆变泛型类型参数的泛型接口称为变体。
正如所指出的,您可以使用以下方法使其工作:
public class P { }
public class B : P { }
public class A : P { }
public interface Interface<out T> where T : P { }
public class IA : Interface<A> { }
public class IB : Interface<B> { }
public class Test
{
public void WhatTheFuck()
{
Interface<P> p;
p = new IA();// cast error here
p = new IB();// cast error here
//... somthing about interface<p>
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 out 关键字声明泛型类型参数协变。协变类型必须满足以下条件:
该类型仅用作接口方法的返回类型,而不用作方法参数的类型。
该类型不用作接口方法的通用约束。这在以下代码中进行了说明。