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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    leetcode第26题--Remove Duplicates from Sorted Array
    leetcode第25题--Remove Element
    leetcode第24题--Reverse Nodes in k-Group
    leetcode第23题--Swap Nodes in Pairs
    leetcode第22题--Merge k Sorted Lists
    leetcode第21题--Generate Parentheses
    leetcode第20题--Valid Parentheses
    leetcode第19题--Remove Nth Node From End of List
    leetcode第18题--Letter Combinations of a Phone Number
    leetcode第17题--4Sum
  • 原文地址:https://www.cnblogs.com/yefengmeander/p/2887759.html
Copyright © 2011-2022 走看看