简体   繁体   English

创建接口时的差异

[英]Variance when creating interfaces

  public interface SomeInterfaceName<out T> where T : struct
  {
    T? SomePropertyName { get; }
  }

The error I get is: 我得到的错误是:

error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'SomeInterfaceName.SomePropertyName'. 错误CS1961:无效方差:类型参数“T”必须在“SomeInterfaceName.SomePropertyName”上不变地有效。 'T' is covariant. 'T'是协变的。

I do not need this to be Covariant. 不需要这是Covariant。 I could as well delete the out keyword. 我也可以删除out关键字。 But then Resharper is suggesting I could use Covariance and I agree, I don't see why I could not. 但是后来Resharper暗示我可以使用Covariance并且我同意,我不明白为什么我不能。 I'm only using T as return value. 我只使用T作为返回值。 Or is it because Nullable<> does not support it? 或者是因为Nullable <>不支持它?

Can anybody explain the error? 任何人都可以解释错误吗?

It's pointless to make a type parameter with a struct constraint covariant. 使用struct约束协变来创建一个类型参数是没有意义的。 Generic variance isn't supported for value type type arguments at all - so for example, there's no conversion from IEnumerable<int> to either IEnumerable<long> or IEnumerable<object> even though there are conversions from int to both long and object . 根本不支持值类型类型参数的通用方差 - 例如,即使存在从intlongobject的转换,也没有从IEnumerable<int>IEnumerable<long>IEnumerable<object>的转换。

The problem you're actually running into is that Nullable<T> isn't covariant, but you're trying to use T in a property of type Nullable<T> . 您实际遇到的问题是Nullable<T>不是协变的,但您尝试在Nullable<T>类型的属性中使用T That's what's causing the error. 这就是导致错误的原因。

Personally I think it would be better if type parameters with struct constraints couldn't be declared to be covariant or contravariant (given that it won't be useful) but that in itself isn't prohibited. 我个人认为如果带有struct约束的类型参数不能被声明为协变或逆变(假设它没有用)会更好,但这本身并不是禁止的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM