博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# Type.GetConstructor() 根据构造函数参数获取实例对象(一)
阅读量:7009 次
发布时间:2019-06-28

本文共 9636 字,大约阅读时间需要 32 分钟。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Kernel.Interface{    public interface IObjcet    {        void Put();        void Put(string plus);    }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Kernel.Interface;namespace Kernel.SimpleLibrary{    public class PlugPut : IObjcet    {        private string plugName = "my plugName value is default!";        public string PlugName        {            get { return plugName; }            set { plugName = value; }        }        public PlugPut() { }                     public PlugPut(string plusName)         {            this.PlugName = plusName;        }        public void Put()        {            Console.WriteLine("Default plug value is:" + plugName);        }        public void Put(string plus)        {            Console.WriteLine("Put plus value is:" + plus);        }    }}
using Kernel.DriverLibrary;using Kernel.Interface;using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace Kernel.TypeLibrary{    public class TypeHelper    {        public static object CreateObject
(params object[] args) where T : 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()); //Console.WriteLine(constructorInfoObj.ToString()); //调用指定参数的构造函数 obj = constructorInfoObj.Invoke(param); } else { Console.WriteLine("The constructor of PlugPut that takes an integer as a parameter is not available."); //myType is System.Type.GetType("Kernel.SimpleLibrary.PlugPut,Kernel.SimpleLibrary") //Activator.CreateInstance(System.Type.GetType("Kernel.SimpleLibrary.PlugPut,Kernel.SimpleLibrary"), null); obj = Activator.CreateInstance(myType, null); } return obj; } catch (Exception) { throw; } } }}
using System;using System.Collections.Generic;using System.Globalization;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace Kernel.DriverLibrary{    public class CustomBinder : Binder    {        public override MethodBase BindToMethod(            BindingFlags bindingAttr,            MethodBase[] match,            ref object[] args,            ParameterModifier[] modifiers,            CultureInfo culture,            string[] names,            out object state)        {            if (match == null)            {                throw new ArgumentNullException("match");            }            // Arguments are not being reordered.            state = null;            // Find a parameter match and return the first method with            // parameters that match the request.            foreach (MethodBase mb in match)            {                ParameterInfo[] parameters = mb.GetParameters();                if (ParametersMatch(parameters, args))                {                    return mb;                }            }            return null;        }        public override FieldInfo BindToField(BindingFlags bindingAttr,            FieldInfo[] match, object value, CultureInfo culture)        {            if (match == null)            {                throw new ArgumentNullException("match");            }            foreach (FieldInfo fi in match)            {                if (fi.GetType() == value.GetType())                {                    return fi;                }            }            return null;        }        public override MethodBase SelectMethod(            BindingFlags bindingAttr,            MethodBase[] match,            Type[] types,            ParameterModifier[] modifiers)        {            if (match == null)            {                throw new ArgumentNullException("match");            }            // Find a parameter match and return the first method with            // parameters that match the request.            foreach (MethodBase mb in match)            {                ParameterInfo[] parameters = mb.GetParameters();                if (ParametersMatch(parameters, types))                {                    return mb;                }            }            return null;        }        public override PropertyInfo SelectProperty(            BindingFlags bindingAttr,            PropertyInfo[] match,            Type returnType,            Type[] indexes,            ParameterModifier[] modifiers)        {            if (match == null)            {                throw new ArgumentNullException("match");            }            foreach (PropertyInfo pi in match)            {                if (pi.GetType() == returnType &&                    ParametersMatch(pi.GetIndexParameters(), indexes))                {                    return pi;                }            }            return null;        }        public override object ChangeType(            object value,            Type myChangeType,            CultureInfo culture)        {            try            {                object newType;                newType = Convert.ChangeType(value, myChangeType);                return newType;            }            // Throw an InvalidCastException if the conversion cannot            // be done by the Convert.ChangeType method.            catch (InvalidCastException)            {                return null;            }        }        public override void ReorderArgumentArray(ref object[] args,            object state)        {            // No operation is needed here because BindToMethod does not            // reorder the args array. The most common implementation            // of this method is shown below.            // ((BinderState)state).args.CopyTo(args, 0);        }        // Returns true only if the type of each object in a matches        // the type of each corresponding object in b.        private bool ParametersMatch(ParameterInfo[] a, object[] b)        {            if (a.Length != b.Length)            {                return false;            }            for (int i = 0; i < a.Length; i++)            {                if (a[i].ParameterType != b[i].GetType())                {                    return false;                }            }            return true;        }        // Returns true only if the type of each object in a matches        // the type of each corresponding entry in b.        private bool ParametersMatch(ParameterInfo[] a, Type[] b)        {            if (a.Length != b.Length)            {                return false;            }            for (int i = 0; i < a.Length; i++)            {                if (a[i].ParameterType != b[i])                {                    return false;                }            }            return true;        }    }}
using Kernel.DriverLibrary;using Kernel.Interface;using Kernel.SimpleLibrary;using Kernel.TypeLibrary;using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Runtime.Remoting;using System.Text;using System.Threading.Tasks;namespace Kernel.App{    class Program    {        static void Main(string[] args)        {            #region            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); #endregion Console.ReadLine(); } }}

 

转载地址:http://erjtl.baihongyu.com/

你可能感兴趣的文章
Java基础学习总结(14)——Java对象的序列化和反序列化
查看>>
Java8 十大新特性详解
查看>>
RHEL7修改root密码
查看>>
mysql8.0.11安装、启动与基本设置
查看>>
大型网站技术架构(五)网站高可用架构
查看>>
Yum编译安装Error Downloading Packages报错
查看>>
Linux创建分区开机自动挂载
查看>>
碧生源牌常润茶 商品库存调整
查看>>
求两个字符串的最长公共子字符串
查看>>
Linux下Mysql数据库备份和恢复全攻略
查看>>
font-family常用字体列表
查看>>
Windows 2012部署活动目录
查看>>
我的友情链接
查看>>
go语言编程音乐库代码
查看>>
将UltraEdit添加到右键菜单
查看>>
QML入门教程(3)
查看>>
es学习3-refresh
查看>>
最实用的播放器
查看>>
我的友情链接
查看>>
Extjs 和 SpringMVC 结合后,Extjs的Ajax回调函数无响应
查看>>