参数必须是输入安全错误

参数必须是输入安全错误

本文介绍了参数必须是输入安全错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 这是我的一部分代码:public interface IA<in TInput>{ void Method(IB<TInput> entities);}public interface IB<in T> { }我不知道为什么会出现以下编译错误: Parameter无效的差异:类型参数| TInput |必须在 IB< IBI can't figure out why I get following compile error:"Parameter must be input-safe. Invalid variance: The type parameter |TInput| must be contravariantly valid on "IB< in T>".任何帮助将不胜感激。推荐答案在C#中使用逆变的指示符(即在$code>中的)在您使用接受泛型类型的参数的方法时才直观。但是,自变量表示关系的反演(问题与解答附有解释),因此使用 IA 中的 in 使其与 IB 不兼容。The designator of contravariance in C# (i.e. in) is intuitive only at the immediate level, when you make a method that "takes in" a parameter of generic type. Internally, however, contravariance means an inversion of a relation (Q&A with an explanation) so using in inside IA makes it incompatible with IB.问题最好用一个例子来说明。考虑类 Animal 及其派生类 Tiger 。我们还假设 IB< T> 具有方法 void MethodB(T input) ,这是从 IA 的方法:The problem is best illustrated with an example. Consider class Animal and its derived class Tiger. Let's also assume that IB<T> has a method void MethodB(T input), which is called from IA's Method:class A_Impl<T> : IA<T> { T data; public void Method(IB<TInput> entities) { entities.MethodB(data); }}在TInput中声明 IA< ; 和 IB< TInput> 表示您可以做到Declaring IA<in TInput> and IB<in TInput> means that you can doIA<Animal> aForAnimals = new A_Impl<Animal>();IA<Tiger> aForTigers = aForAnimals; IA< TInput> 有一个方法它需要 IB< TInput> ,我们可以这样称呼它:IA<in TInput> has a method that takes IB<TInput>, which we can call like this:aForTigers.Method(new B_Impl<Tiger>());这是一个问题,因为现在 A_Impl< Animal> 将 Animal 传递给需要 Tiger MethodB c $ c>。This is a problem, because now A_Impl<Animal> passes an Animal to MethodB of an interface that expects a Tiger.尽管 IB< out T> 您不会有问题-两者均具有协方差和协变:You would have no problem with IB<out T>, though - both with covariance and contravariance:public interface IB<out T> {// ^^^}// This workspublic interface IA<in TInput> { void Method(IB<TInput> x);}// This works toopublic interface IC<out TInput> { void Method(IB<TInput> x);} 这篇关于参数必须是输入安全错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-04 01:59