Create an object knowing only the class name?

后端 未结 5 1289
花落未央
花落未央 2020-12-15 22:16

I have a set of classes, each one is a different strategy to do the same work.

namespace BigCorp.SuperApp
{
    public class BaseClass { }
    public class          


        
5条回答
  •  情书的邮戳
    2020-12-15 22:42

    Either use the assembly-qualified-name, or get hold of the Assembly and use Assembly.GetType(name). In this case, since you want the types in the config file, assembly-qualified is a valid way to go - but since you know all your types are in the same assembly:

    Assembly assembly = typeof(SomeKnownType).Assembly; // in the same assembly!
    Type type = assembly.GetType(name); // full name - i.e. with namespace (perhaps concatenate)
    object obj = Activator.CreateInstance(type);
    

    The static Type.GetType(string) has probing rules that often cause confusion... it looks at the calling assembly, and a few system assemblies - but not all loaded assemblies.

提交回复
热议问题