NET 基于反射,实例化泛型对象

1.基于反射,实例化泛型对象:Activator

        public static T GetInStance<T>()
        {
            var ob = Activator.CreateInstance<T>();
            return ob;
        }

2.通过类型约束

        public static T GetInStance2<T>() where T : class, new()
        {
            var ob = new T();
            return ob;
        }

3.基于反射,实例化泛型对象:Assembly

        public static object GetInStance3()
        {
            // 程序集
            var assemblyName = "ProjectAssemblyName";
            // 命名空间.类型名
            var fullName = $"ProjectAssemblyName.CustClass";
            // 加载程序集,创建程序集里面的 命名空间.类型名 实例
            object ob = Assembly.Load(assemblyName).CreateInstance(fullName); ;
            return ob;
        }

4.demo

        public TestGenericProgram(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
        {

        }
        [Fact]
        public void Run()
        {
            var ob = new CustClass();
            var ob1 = GenericClass.GetInStance<CustClass>();
            var ob2 = GenericClass.GetInStance2<CustClass>();
            var ob3 = GenericClass.GetInStance3();

            //ob: { "Code":0,"Name":null}
            //ob1: { "Code":0,"Name":null}
            //ob2: { "Code":0,"Name":null}
            //ob3: { "Code":0,"Name":null}
            _testOutputHelper.WriteLine($"ob:{ob.ToJson()}");
            _testOutputHelper.WriteLine($"ob1:{ob1.ToJson()}");
            _testOutputHelper.WriteLine($"ob2:{ob2.ToJson()}");
            _testOutputHelper.WriteLine($"ob3:{ob3.ToJson()}");
        }
    }

    public class GenericClass
    {
        public static T GetInStance<T>()
        {
            var ob = Activator.CreateInstance<T>();
            return ob;
        }

        public static T GetInStance2<T>() where T : class, new()
        {
            var ob = new T();
            return ob;
        }

        public static object GetInStance3()
        {
            // 程序集
            var assemblyName = "ProjectAssemblyName";
            // 命名空间.类型名
            var fullName = $"ProjectAssemblyName.CustClass";
            // 加载程序集,创建程序集里面的 命名空间.类型名 实例
            object ob = Assembly.Load(assemblyName).CreateInstance(fullName); ;
            return ob;
        }
    }
View Code

 

posted @ 2021-09-06 14:12  Robot-Blog  阅读(147)  评论(0编辑  收藏  举报