我试图IList<T>
通过他们的类型比较两个.两个列表都相同T
,因此我认为它们应该具有相同的类型.
在工具提示中的Visual Studio中的调试模式中,我可以读取两者的类型,它是相同的.
但Equals()
蚂蚁==
运营商同时返回false
.
任何人都能解释这种疲惫的行为吗?
小例子:
class Program
{
static void Main(string[] args)
{
IList<string> list1 = new List<string>();
IList<string> list2 = new List<string>();
var type1 = list1.GetType();
var type2 = typeof(IList<string>);
if (type1.Equals(type2))
{
Console.WriteLine("equal");
}
else
{
Console.WriteLine("non equal");
}
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
==>不等于
编辑: 我写了一个不好的例子,这个显示了我尝试的方式.
我正在使用.Net 3.5
是的,你要比较两种类型:List<string>
和IList<string>
.它们不是同一类型,我不知道你为什么期望它们是相同的.
目前还不清楚你要做什么,但你可能想要使用Type.IsAssignableFrom
.例如,在您的示例中,
Console.WriteLine(type2.IsAssignableFrom(type1));
Run Code Online (Sandbox Code Playgroud)
将打印为True.
在编辑之前回答......
无法重现:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
IList<string> list1 = new List<string>();
IList<string> list2 = new List<string>();
var type1 = list1.GetType();
var type2 = list2.GetType();
Console.WriteLine(type1.Equals(type2)); // Prints True
}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能在您的实际代码中,它们既是实现IList<string>
,又是不同的实现,例如
IList<string> list1 = new List<string>();
IList<string> list2 = new string[5];
Run Code Online (Sandbox Code Playgroud)
这将显示不同的类型,因为一个是a List<string>
而另一个是a string[]
.