考虑以下示例:classBase{}classDerived:Base{}classTest1{privateListm_X;publicIEnumerableGetEnumerable(){returnm_X;}}这编译得很好,因为IEnumerable在T中协变.但是,如果我做完全相同的事情,但现在使用泛型:classTest2whereTDerived:TBase{privateListm_X;publicIEnumerableGetEnumerable(){returnm_X;}}编译错误Cannotconvertexpressiontype'System.Collection
我为我们的项目添加了一个协变接口(interface):interfaceIView{}interfaceIPresenterwhereTView:IView{TViewView{get;}}我创建了一些类,实现了这些接口(interface):classTestView:IView{}classTestPresenter:IPresenter{publicTestViewView{get{returnsomething;}}privatevoidDoSomething(){}}我可以毫无问题地使用它:IPresenterpresenter=newTestPresenter();所以一
给定以下类型:publicinterfaceIMyClass{}publicclassMyClass:IMyClass{}我想知道如何转换List到List?我对协变/逆变主题不是很清楚,但我知道我不能因此而简单地使用List。我只能想出这个微不足道的解决方案;缺乏优雅,浪费资源:...publicListConvertItems(Listinput){varresult=newList(input.Count);foreach(varitemininput){result.Add(item);}returnresult;}....如何以更优雅/更高效的方式解决它?(请注意,我需要.N
如果我为值类型实现一个接口(interface)并尝试将其转换为它的接口(interface)类型的列表,为什么这会导致错误而引用类型转换得很好?这是错误:CannotconvertinstanceargumenttypeSystem.Collections.Generic.ListtoSystem.Collections.Generic.IEnumerable我必须明确地使用Cast转换它的方法,为什么?自IEnumerable是通过集合的只读枚举,它不能直接转换对我来说没有任何意义。下面是演示该问题的示例代码:publicinterfaceI{}publicclassT:I{}pu
C#4.0将支持协变和逆变。但是我并不清楚这个新特性的好处。你能(清楚地)解释一下我们为什么需要它吗? 最佳答案 它们只允许您做一些概念上有效且形式上可接受的事情,但由于语言限制目前不允许这样做。例如:IEnumerableints=newList{1,2,3};Action>PrintThings=x=>{foreach(varthinginx)Console.WriteLine(thing);};PrintThings(ints);//doesn'tcompilerightnow:(willcompilein4.0没有根本原因说
鉴于这个神奇的界面:publicinterfaceIHat{TRabbitTake();}这个类的层次结构:publicclassRabbit{}publicclassWhiteRabbit:Rabbit{}我现在可以编译了:IHathat1=null;IHathat2=hat1;太棒了。但是,如果我以不同的方式定义接口(interface)会怎样:publicinterfaceIHat{boolTake(outTRabbitr);}我表示帽子可能是空的,使用单独的bool返回值(以前的版本可能会从空帽子返回nullrabbit)。但我仍然只输出一只兔子,所以没有做任何逻辑上与以前版本
这个问题在这里已经有了答案:HowtocastExpression>toExpression>(4个答案)关闭9年前。有没有更快的方法来转换Fun至FuncpublicstaticclassStaticAccessors{publicstaticFuncTypedGetPropertyFn(PropertyInfopi){varmi=pi.GetGetMethod();return(Func)Delegate.CreateDelegate(typeof(Func),mi);}publicstaticFuncValueUnTypedGetPropertyTypeFn(PropertyIn
例如IEnumerable界面:publicinterfaceIEnumerable:IEnumerable{IEnumeratorGetEnumerator();}在此接口(interface)中,泛型仅用作接口(interface)方法的返回类型,不用作方法参数的类型,因此它可以是协变的。鉴于此,编译器理论上不能从接口(interface)中推断出差异吗?如果可以,为什么C#要求我们显式设置co/contravariance关键字。更新:正如JonSkeet提到的,这个问题可以分解为子问题:编译器能否通过在当前泛型类型及其所有基类型中使用泛型类型来推断泛型类型的协变/逆变?例如..
理解关于重载决议的C#语言规范显然很难,现在我想知道为什么这个简单的案例失败了:voidMethod(Funcf){}voidMethod(Funcf){}voidCall(){Method(()=>{thrownewNotSupportedException();});}这会产生编译时错误CS0121,以下方法或属性之间的调用不明确:后跟我的两个Method函数成员(重载)。我所期望的是Func是一个比Func更好的转换目标,然后应该使用第一个重载。自.NET4和C#4(2010)起,通用委托(delegate)类型Func在TResult中一直协变,因此存在从Func的隐式转换至F
这个问题在这里已经有了答案:QuestionaboutC#covariance(4个答案)关闭9年前。考虑代码片段。IListobj=newList();IEnumerableobj1=obj;但是如果我写ICollectionobj2=obj;它抛出一个编译时错误。Cannotimplicitlyconverttype'System.Collections.Generic.IList'to'System.Collections.Generic.ICollection'.为什么自List以来出现此行为同时实现IEnumerable和ICollection还有IList定义为public