gpt4 book ai didi

c# - 如何检查 `IEnumerable` 是否与 `IEnumerable` 协变?

转载 作者:太空狗 更新时间:2023-10-29 20:19:46 25 4
gpt4 key购买 nike

检查 IEnumerable<T1> 的通用规则是什么?与 IEnumerable<T2> 协变?

我做了一些实验:


1.

Object Obj = "Test string";
IEnumerable<Object> Objs = new String[100];

因为 IEnumerable<out T> 有效是协变的并且 String继承Object .

2.

interface MyInterface{}
struct MyStruct:MyInterface{}
.....
Object V = new MyStruct();
Console.WriteLine(new MyStruct() is Object); // Output: True.
IEnumerable<Object> Vs = new MyStruct[100]; // Compilation error here

MyStruct实际上是一个 Object , 但它不起作用,因为 Object是引用类型,MyStruct是值类型。好的,我在这里看到了一些逻辑。

3.

Console.WriteLine(new MyStruct() is ValueType); // Output: "True"
ValueType V2 = new MyStruct();
IEnumerable<ValueType> Vs2 = new MyStruct[100]; // Compilation error here

应该可以工作,因为 IEnumerable<out T>是协变的并且 MyStructValueType ,但不起作用......好吧,也许MyStruct实际上并没有继承ValueType ....

4.

MyInterface V3 = new MyStruct(); 
Console.WriteLine(V3 is MyInterface); // Output: "True"
IEnumerable<MyInterface> Vs3 = new MyStruct[100]; // Compilation error here

即使这样:“无法将 MyStruct 转换为 MyInterface”。哦真的吗??你刚刚在一行之前做了......


我试图制定通用规则:

public static bool IsCovariantIEnumerable(Type T1, Type T2  ){          
return (T2.IsAssignableFrom(T1)) && !T2.IsValueType; // Is this correct??
}

所以,问题是如何实际确定 IEnumerable<T1>IEnumerable<T2> 协变?是我的IsCovariantIEnumerable(...)功能正确?如果是,有没有更简单的方法来检查它?如果不是,如何解决?

另请参阅这些文章:1 , 2 .

最佳答案

在您的特定情况下它不起作用,因为值类型不支持协方差。

但是对于如何确定是否 一个IEnumerable<T2> 的问题是 IEnumerable<T1> 的协变体:

方法Type.IsAssignableFrom()告诉您某种类型的实例是否可分配给这种类型的变量。所以你可以像这样实现你的方法:

public static bool IsCovariantIEnumerable(Type T1, Type T2)
{
Type enumerable1 = typeof(IEnumerable<>).MakeGenericType(T1);
Type enumerable2 = typeof(IEnumerable<>).MakeGenericType(T2);
return enumerable1.IsAssignableFrom(enumerable2);
}

用法:

if (IsCovariantIEnumerable(typeof(object), typeof(string))
Console.WriteLine("IEnumerable<string> can be assigned to IEnumerable<object>");

但是IsCovariantIEnumerable(typeof(object), typeof(MyStruct))将返回 false出于上述原因。


为了完整性:当然你不需要额外的方法,因为你可以很容易地做到typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<string>) .

关于c# - 如何检查 `IEnumerable<T1>` 是否与 `IEnumerable<T2>` 协变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39225640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com