簡單的代碼,我期望List<int>
的GenericTypeDefinition包含一個通用接口ICollection<>
。然而,我無法從List<int>
中推導出可接受的類型,這使我可以正確地比較它們。比較接口的GenericTypeDefinition
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var a = typeof(List<int>);
var b = typeof(ICollection<>);
var r1 = a.GetGenericTypeDefinition().GetInterfaces();
foreach (var x in r1)
{
Console.WriteLine(x);
}
Console.WriteLine();
Console.WriteLine(b);
Console.WriteLine();
Console.WriteLine(r1.Any(x => x == b));
}
}
輸出
System.Collections.Generic.IEnumerable`1[T]
System.Collections.Generic.IReadOnlyList`1[T]
System.Collections.Generic.IReadOnlyCollection`1[T]
System.Collections.IEnumerable
System.Collections.Generic.IList`1[T]
System.Collections.Generic.ICollection`1[T]
System.Collections.ICollection
System.Collections.IList
System.Collections.Generic.ICollection`1[T]
False
我本來預計r1
包含一種類型,是等於b
。
編輯
固定的,喬恩斯基特給了我正確的洞察到發生了什麼事。
using System;
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var a = typeof(List<int>);
var b = typeof(ICollection<>);
var r1 = a.GetInterfaces()
.Where(x => x.IsGenericType)
.Select(x => x.GetGenericTypeDefinition());
foreach (var x in r1)
{
Console.WriteLine(x);
}
Console.WriteLine();
Console.WriteLine(b);
Console.WriteLine();
Console.WriteLine(r1.Contains(b));
}
}
輸出
System.Collections.Generic.IEnumerable`1[T]
System.Collections.Generic.IReadOnlyList`1[T]
System.Collections.Generic.IReadOnlyCollection`1[T]
System.Collections.Generic.ICollection`1[T]
System.Collections.Generic.IList`1[T]
System.Collections.Generic.ICollection`1[T]
True
謝謝你,你給了我我需要的見解。 – 2015-03-03 10:14:13