zoukankan      html  css  js  c++  java
  • Type.GetType(string typeName) returns null !?

    Type.GetType gives us the ability to get type back from a string. We pass a well-written type name string to it, and expect it return that type. Sometimes, to your surprise, it returns null. For example, Type.GetType("System.Data.SqlClient.SqlException").

    If the assembly name is specified in the typeName string, Type.GetType() will search inside this assembly only; otherwise, it tries to find one in the caller assembly and then the system assembly (mscorlib.dll). Anything after ',' in the typeName string is treated as assembly name. In previous example, no assembly name was specified; neither the caller nor mscorlib had a type of SqlException, Type.GetType did indeed find nothing in its search. To make it work, we need specify System.Data.dll in typeName. In contrast, Type.GetType("System.Int32") can return type System.Int32 without mentioning mscorlib.dll.

    Type.AssemblyQualifiedName is a right way to tell what kind of typeName we should provide. typeof(System.Data.SqlClient.SqlException).AssemblyQualifiedName is "System.Data.SqlClient.SqlException, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089". Type.GetType with this long string will succeed in .NET 2.0.

    Note that in .NET, namespace and assembly name are not necessarily related. Type "System.Data.SqlClient.SqlException" is not with System.Data.SqlClient.dll (which does not exist, by the way). The separation is one reason why Type.GetType(typeName) tries not to guess which assembly should be loaded and then searched based on the type's namespace.

    Other things good to mention here:

    1. To get back a generic type, the typeName needs be like "System.Collections.Generic.List`1", where the mark is `(grave accent), not '(quotation mark). Writing with the wrong mark will be likely to cause Type.GetType returning null too.
    2. If we prefer throwing exception to returning null, use the overload method Type.GetType(typeName, throwOnError)
    3. More information on this API, please go search MSDN . Yiru also has a further discussion on the type name grammar here .
    作者:Angelo Lee
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    【Vijos1159】岳麓山上打水 [迭代加深]
    【POJ3134】 Power Calculus [迭代加深]
    【2019.1.24】 搜索,动规 经典题目体验赛
    【noip2017】
    【poj3311】Hie With The Pie [状压dp]
    [bzoj3938] [Uoj #88] Robot
    [洛谷P4707] 重返现世
    [洛谷P4097] [HEOI2013] Segment
    KD-tree 学习小记
    NOI2019 酱油记
  • 原文地址:https://www.cnblogs.com/yefengmeander/p/2887759.html
Copyright © 2011-2022 走看看