通过反射,创建类的实例三

这次我们通过构造函数的方式处理

using System;
using System.Reflection;

namespace App
{
    public class TypeHelper
    {
        public static object CreateObject(params object[] args) where T : Interface.IObjcet
        {
            try
            {
                Type myType = typeof(T);

                int lenght = 0;
                if (args != null)
                {
                    lenght = args.Length;
                }

                Type[] types = new Type[lenght];
                for (int i = 0; i < args.Length; i++)
                {
                    types[i] = args[i].GetType();
                }

                object[] param = new object[lenght];
                for (int i = 0; i < args.Length; i++)
                {
                    param[i] = args[i];
                }

                object obj = null;

                // Get the constructor that takes an integer as a parameter.
                ConstructorInfo constructorInfoObj = myType.GetConstructor(types);

                //ConstructorInfo constructorInfoObj = myType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, types, null);
                //ConstructorInfo constructorInfoObj = myType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null,CallingConventions.HasThis, types, null);

                //CustomBinder customBinder = new CustomBinder();
                //ConstructorInfo constructorInfoObj = myType.GetConstructor(BindingFlags.Instance | BindingFlags.Public, customBinder, CallingConventions.HasThis, types, null);

                if (constructorInfoObj != null)
                {
                    Console.WriteLine("The constructor of PlugPut that takes an integer as a parameter is: " + constructorInfoObj.ToString());
                    //调用指定参数的构造函数
                    obj = constructorInfoObj.Invoke(param);
                }
                else
                {
                    Console.WriteLine("The constructor of PlugPut that takes an integer as a parameter is not available.");
                    obj = Activator.CreateInstance(myType, null);
                }
                return obj;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("");

        Test1();

        Console.ReadLine();
    }

    static void Test1()
    {
        Console.Write("Put plus value is:");
        string strPlus = Console.ReadLine();

        //无参构造函数
        IObjcet obj = (IObjcet)TypeHelper.CreateObject();
        obj.Put();
        obj.Put(strPlus);

        //定义构造函数所需参数
        object[] param = new object[1];
        param[0] = strPlus;

        //带参数的构造函数
        obj = (IObjcet)TypeHelper.CreateObject(param);
        obj.Put();
        obj.Put(strPlus);
    }

    ......

通过反射,创建类的实例三_第1张图片

你可能感兴趣的:(C#)