C# 理解C语言中的逆变#
我正在学习逆变,并尝试以下方法来吸收这个概念:C# 理解C语言中的逆变#,c#,contravariance,C#,Contravariance,我正在学习逆变,并尝试以下方法来吸收这个概念: interface B<T> { T h(); } public class SomeOtherClass<T> : B<T> { public T h() { return default(T); } } public class Trial { static void Main() { SomeOtherClass<De
interface B<T>
{
T h();
}
public class SomeOtherClass<T> : B<T>
{
public T h()
{
return default(T);
}
}
public class Trial
{
static void Main()
{
SomeOtherClass<Derived> h = new SomeOtherClass<Derived>();
Base b = h.h();
}
}
接口B
{
th();
}
公共类其他类:B
{
公共T h()
{
返回默认值(T);
}
}
公开庭审
{
静态void Main()
{
SomeOtherClass h=新的SomeOtherClass();
基b=h.h();
}
}
我原以为这段代码会在最后一条语句中出错,并认为使用T逆变可以修复它。然而,这是按原样工作的。让我想知道逆变在哪里适用?泛型变量在接口和Delgate中使用 将您的代码更改为以下,您将开始获得错误
public class Trial
{
static void Main()
{
B<Derived> h = new SomeOtherClass<Derived>();
B<Base> b = h; // you will get compilation error until you add out keyword in interface B
}
}
公开课审判
{
静态void Main()
{
B h=新的SomeOtherClass();
B=h;//在接口B中添加关键字之前,将出现编译错误
}
}
Here out(Contravariant)关键字是告诉编译器B的实例可以安全地被认为是B的一种方式您可以看看这里,这篇文章包含一些示例和解释。
using System;
using static System.Console;
////
namespace ConsoleApplication1
{
interface iContravariance<in T>
{
void Info(T t);
}
class Master<T> : iContravariance<T>
{
public void Info(T insT)
{
if (insT is Parent) {
WriteLine("--- As Parent: ---");
WriteLine((insT as Parent).Method());
}
if (insT is Child) {
WriteLine("--- As Child: ---") ;
WriteLine((insT as Child).Method());
}
}
}
class Parent {
public virtual String Method()
{
WriteLine("Parent Method()");
return "";
}
}
class Child : Parent {
public override String Method()
{
WriteLine("Child Method()");
return "";
}
}
class Client
{
static void Main(string[] args)
{
Child child = new Child();
Parent parent = new Parent();
iContravariance<Parent> interP = new Master<Parent>();
iContravariance<Child> interC = interP;
interC.Info(child);
//interC.Info(parent); (It is compilation error.)
ReadKey();
return;
}
}
}
--- As Parent: ---
Child Method()
--- As Child: ---
Child Method()