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
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    判断一个字符串之中出现次数最多的字符和它出现的次数
    冒泡排序
    vue 页面生成图片保存
    css实现0.5像素的底边框。
    web之面试常问问题:如何实现水平垂直居中?
    cocos 向左滚动公告
    SpringBoot 访问jsp文件报错Path with "WEB-INF" or "META-INF": [WEB-INF/jsp/welcome.jsp]的解决办法
    vue 弹窗禁止底层滚动
    vue 倒计时 iOS无效
    axios之增删查改操作
  • 原文地址:https://www.cnblogs.com/yefengmeander/p/2887759.html
Copyright © 2011-2022 走看看