Comparing types of generic lists
I'm trying to compare two IList<T>
by their Type. Both lists have the same T
and therefore I thought they should have the same type.
In debug-mode in Visual Studio in the tooltip I can read the types of both and it is the same.
But Equals()
ant the ==
Operator return both false
.
Can anyone explanin this weired behavior?
Little Example:
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
开发者_JS百科 {
Console.WriteLine("non equal");
}
Console.ReadLine();
}
}
==> non equal
Edit: I coose a bad Example, this one shows the way I was trying to to it.
I'm using .Net 3.5
Yes, you're comparing two types: List<string>
and IList<string>
. They're not the same type, and I don't know why you'd expect them to be the same.
It's unclear what you're trying to do, but you might want to use Type.IsAssignableFrom
. For example, in your example,
Console.WriteLine(type2.IsAssignableFrom(type1));
will print True.
Answer from before the edit...
Unable to reproduce:
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
}
}
Is it possible that in your real code, they're both implementations of IList<string>
, but different implementations, e.g.
IList<string> list1 = new List<string>();
IList<string> list2 = new string[5];
That will show the types being different, because one is a List<string>
and the other is a string[]
.
That is because list1 is List<string>
( so type1 is typeof(List<string>)
aswell ) and type 2 is typeof(IList<string>)
. Notice IList<string>
vs List<string>
. Neither list1
nor list2
is IList<string>
, they are List<T>
's, which derives from IList<T>
As mentioned above this is indeed due to the reason that List<string>
and IList<string>
are not the same type.
If your goal is to determine whether your type implements an interface (i.e. IList<string>
) you can do so with reflection:
if (type1.GetInterfaces().Contains(typeof(IList<string>)))
Console.WriteLine("type1 implements IList<string>");
精彩评论