Getting a System.Type from type's partial name

前端 未结 7 858
梦谈多话
梦谈多话 2020-11-27 07:18

I want to get a System.Type given only the type name in a string.

For instance, if I have an object:

MyClass abc = new MyCl         


        
7条回答
  •  囚心锁ツ
    2020-11-27 07:45

    Here is a simple method for creating and initializing a new object from its name and parameters:

        //  Creates and initializes a new object from its name and parameters
        public Object CreateObjectByName(string name, params Object[] args)
        {
            string s = "" + name;    // case sensitive; Type.FullName
            Type type = Type.GetType(s);
            Object o = System.Activator.CreateInstance(type, args);
            return o;
        }
    

    One example of how one might use this is to read a file containing class names [or partial class names] and parameters and then add the objects returned to a list of objects of a base type that is common to the objects created.

    To see what your class name [or ] should look like, temporarily use something like this [if your class is named NewClass]:

        string z = (new NewClass(args)).GetType().FullName;
    

提交回复
热议问题