什么是“在”泛型参数呢? [英] What does an "in" generic parameter do?

查看:109
本文介绍了什么是“在”泛型参数呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



public interface ISomeInterface< in T>



参数中的有什么影响?

解决方案

您可以阅读关于通用差异和反向变化在.NET 4.0中引入。 关键字中的对接口的影响是它声明它是逆变的,意味着只能使用 T 作为输入法的类型。您不能将其用作此接口方法的返回类型。这样做的好处是你可以做这样的事情(如前面提到的文章所示):

  interface IProcessor< ;在T> 
{
void Process(IEnumerable< T> ts);
}

列表<长颈鹿>长颈鹿=新列表<长颈鹿> {new Giraffe()};
列表< Whale>鲸鱼=新列表< Whale> {new Whale()};
IProcessor< IAnimal> animalProc =新处理器< IAnimal>();
IProcessor< Giraffe> giraffeProcessor = animalProc;
IProcessor< Whale> whaleProcessor = animalProc;
giraffeProcessor.Process(长颈鹿);
whaleProcessor.Process(whales);


Saw this signature today:

public interface ISomeInterface<in T>

What impact does the in parameter have?

解决方案

You could read about generic variance and contravariance introduced in .NET 4.0. The impact that the in keyword has on the interface is that it declares it as contravariant meaning that T can only be used as input method type. You cannot use it as return type on the methods of this interface. The benefit of this is that you will be able to do things like this (as shown in the aforementioned article):

interface IProcessor<in T>  
{  
    void Process(IEnumerable<T> ts);  
}

List<Giraffe> giraffes = new List<Giraffe> { new Giraffe() };  
List<Whale> whales = new List<Whale> { new Whale() };  
IProcessor<IAnimal> animalProc = new Processor<IAnimal>();  
IProcessor<Giraffe> giraffeProcessor = animalProc;  
IProcessor<Whale> whaleProcessor = animalProc;  
giraffeProcessor.Process(giraffes);  
whaleProcessor.Process(whales);  

这篇关于什么是“在”泛型参数呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆