When does `Assembly.GetType(name)` return `null`?

后端 未结 6 1783
太阳男子
太阳男子 2021-01-12 17:47

I have a code like shown below

public static Type ToType(Type sType)
{    
    Assembly assembly = Assembly.Load(SerializableType.AssemblyName);
    type = a         


        
6条回答
  •  长情又很酷
    2021-01-12 18:00

    This is not working just because you load code from other assembly than you base class assembly. Trying to call this code from other assembly than contains definiton of searched type will result in type resolved to null.

    It is reasonable, because you have to provide an assembly qualified type name, i.e. Type.AssemblyQualifiedName, not just type full name itself

    If you derived classes defined elsewere in another assembly than base class with code sample, your code from assembly where base class is defined will not work.

    This will work


    public static Type ToType(Type type, ITypeResolver typeResolver)
    {    
        Assembly assembly = Assembly.Load(SerializableType.AssemblyName);
        type = typeResolver.GetType(assembly, sType.AssemblyQualifiedName);
    }
    

    You can use a TypeResolver like that (C# 7.2)

    public interface ITypeResolver
    {
        string GetName(Type type);
        Type GetType(Assembly assembly, string typeName);
    }
    
    class TypeResolver : ITypeResolver
    {
        public string GetName(Type type) => type.AssemblyQualifiedName;
        public Type GetType(Assembly assembly, string typeName) =>
            assembly.GetType(typeName) ?? Type.GetType(typeName);
    }
    

    MSDN:

    https://docs.microsoft.com/ru-ru/dotnet/api/system.type.gettype?view=netcore-2.1#System_Type_GetType_System_String_

提交回复
热议问题