- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
检查 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>
是协变的并且 MyStruct
是ValueType
,但不起作用......好吧,也许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(...)
功能正确?如果是,有没有更简单的方法来检查它?如果不是,如何解决?
最佳答案
在您的特定情况下它不起作用,因为值类型不支持协方差。
但是对于如何确定是否 一个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/
COW 不是奶牛,是 Copy-On-Write 的缩写,这是一种是复制但也不完全是复制的技术。 一般来说复制就是创建出完全相同的两份,两份是独立的: 但是,有的时候复制这件事没多大必要
我是一名优秀的程序员,十分优秀!