【问题标题】:Why GetType() is not able to identify this type? [duplicate]为什么 GetType() 不能识别这种类型? [复制]
【发布时间】:2018-08-25 09:59:40
【问题描述】:

这是code:

public class Program
{
    public static void Main(string[] args)
    {
       Test test = new Test();
    }
}

public class Test
{
    public Test() {
        Console.WriteLine("type: " + Type.GetType("Registration"));        
    }
}

public class Registration
{
    public int mAge;
    public string mName;

    public Registration() {}
}  

当它尝试获取Registration 的类型时,它返回null。所以.Name 或.AssemblyQualifiedName 都无法访问。

只有在GetType() 不返回null 时,我才能提供AssemblyQualifiedName。

为什么GetType() 返回null?希望问题很清楚。

【问题讨论】:

    标签: c# types


    【解决方案1】:

    你需要指定类型的全名,包括命名空间:

    Console.WriteLine("type: " + Type.GetType("Rextester.Registration")); 
    

    或者 - 取决于你想要做什么:

    Console.WriteLine("type: " + typeof(Registration)); 
    

    【讨论】:

      【解决方案2】:

      您需要指定“程序集限定”类型名称:

      Type.GetType("YourNameSpace.Registration");
      

      正如documentation 所说:

      类型名称 类型:System.String

      要获取的类型的程序集限定名称。看 装配合格名称。如果类型在当前 执行程序集或在 Mscorlib.dll 中,提供 由其命名空间限定的类型名称。

      【讨论】:

        【解决方案3】:

        效果很好。如果它不适合你,那么可能有一个 namespace,在这种情况下你需要"TheNamespace.Registration"。如果类型在不同的程序集中,您也需要指定 ;最终,最可靠的字符串版本是类型的 AssemblyQualifiedName - 可能类似于 "Registration, ConsoleApp48, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",或者如果涉及强名称,则更长。

        但是,typeof(Registration) 会比这些选项中的任何 更容易。

        【讨论】:

        • 为什么使用不同的命名空间似乎不起作用? rextester.com/XSIKO23415
        • @markzzz 的完全限定名称(不包括装配部分)是WebApi.WebAPIController+Registration(注意+,而不是.)
        • 哦……那是+。为什么在这里+ 而不是.?
        • @markzzz 因为Type.GetType() 需要对任何调用者语言都一样,所以它使用 CLR 的类型名称约定,这与 C# 的类型名称约定不匹配。在 C# 中,嵌套类型是 Outer.Inner。在 CLR 术语中,嵌套类型是 Outer+Inner
        • @markzzz 同样,在 C# 中,List<T> 是:List<T>。到 List`1[[T]] 的 CLR。至于为什么,考虑一下:在VB中是List(Of T);在 F# 中是......我什至不知道是什么
        【解决方案4】:

        我认为你需要为你的类定义完整的命名空间路径,比如TestNamespace.Registration

        【讨论】:

          猜你喜欢
          • 2016-04-18
          • 2018-03-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-20
          • 2020-05-25
          • 1970-01-01
          相关资源
          最近更新 更多