Mã đơn giản mà tôi mong đợi List<int>
'GenericTypeDefinition để chứa giao diện chung của ICollection<>
. Tuy nhiên, tôi không thể lấy được một loại có thể chấp nhận được từ List<int>
cho phép tôi so sánh chúng một cách chính xác.So sánh GenericTypeDefinition của giao diện
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));
}
}
Output
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
tôi lại có thể ngờ rằng r1
chứa một loại đó là bằng b
.
EDIT
cố định, Jon Skeet đã cho tôi cái nhìn sâu sắc ngay vào những gì đang xảy ra.
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));
}
}
Output
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
Cảm ơn bạn, bạn đã cho tôi cái nhìn sâu sắc mà tôi cần. –