Best way to get a Type object from a string in .NET

后端 未结 2 1874
情话喂你
情话喂你 2021-01-12 09:32

What is the best way to convert a string into a Type object in .NET?

Issues to consider:

  • The type may be in a different assembly.
  • The type\'s
相关标签:
2条回答
  • 2021-01-12 09:41

    You can use Type.GetType(string) in order to do this. The type name must be assembly qualified but the method will load the assembly as necessary. The assembly qualification is not necessary if the type is in mscorlid or the assembly which executes the GetType call.

    0 讨论(0)
  • 2021-01-12 09:47

    you might need to call GetReferencedAssemblies() method for the second.

    namespace reflectme
    {
        using System;
        public class hello
        {
            public hello()
            {
                Console.WriteLine("hello");
                Console.ReadLine();
            }
            static void Main(string[] args)
            {
                Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello");
                t.GetConstructor(System.Type.EmptyTypes).Invoke(null);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题