开发者

Why this types are not equal?

开发者 https://www.devze.com 2023-03-06 05:13 出处:网络
using System; using System.Reflection; namespace App { public class A<T> { public WonderfulClass<T> field;
using System;
using System.Reflection;

namespace App
{
  public class A<T>
  {
    public WonderfulClass<T> field;
  }

  public class WonderfulClass<T> { }

  class Programm
  {
    static void Main(string[] args)
    {
      Type t = typeof(A<>);

      Type t1 = t.GetField("field").FieldType;
      Type t2 = typeof(WonderfulClass&开发者_运维问答lt;>);

      //Why t1 and t2 are different?
      Console.WriteLine(t1 == t2 ? "Equal" : "Not Equal");
    }
  }
}


If you inspect the properties, you will notice:

t2.IsGenericTypeDefinition
true
t1.IsGenericTypeDefinition
false

Hence while t2 is an actual definition, t1 has already have it's generic type parameter applied.

Note the following:

t1.GetGenericTypeDefinition() == t2
true


Your confusion is because you have two completely different things with the same name, T. If you said:

class A<T>
{
    B<T> b1;
}
class B<U> 
{
    B<U> b2;
}

now it should be more clear. The compile-time type of A<T>.b1 is B<T>. The compile-time type of B<U>.b2 is B<U>. B<T> and B<U> are different types.

0

精彩评论

暂无评论...
验证码 换一张
取 消