How do I create an instance from a string in C#?

前端 未结 2 2025
既然无缘
既然无缘 2020-11-28 12:56

I\'m reading information from an XML which contains the type of an object that I need to instantiate along with it\'s constructor parameters.

The object type is actu

2条回答
  •  情书的邮戳
    2020-11-28 13:29

    • You need to specify the full type name to Type.GetType(), including namespace, e.g. "Company.Project2.Type"
    • If the type isn't in the same assembly (or mscorlib), you need to give the assembly name too, including version information if it's strongly typed. For example, for a non-strongly typed assembly Company.Project2.dll, you might specify "Company.Project2.Type, Company.Project2".
    • To call a constructor with parameters you can call Activator.CreateInstance(Type, Object[]) or get the exact constructor you want with Type.GetConstructor() and then call ConstructorInfo.Invoke().

    If that doesn't help, please give more information.

提交回复
热议问题