C# Type.GetConstructor() 根据构造函数参数获取实例对象(一)
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<T>(params object[] args) where T : IObjcet
{
try
{
Type myType = typeof(T); int lenght = ;
if (args != null)
{
lenght = args.Length;
} Type[] types = new Type[lenght];
for (int i = ; i < args.Length; i++)
{
types[i] = args[i].GetType();
} object[] param = new object[lenght];
for (int i = ; 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 = ; 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 = ; 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<PlugPut>();
obj.Put();
obj.Put(strPlus); //定义构造函数所需参数
object[] param = new object[];
param[] = strPlus; //带参数的构造函数
obj = (IObjcet)TypeHelper.CreateObject<PlugPut>(param);
obj.Put();
obj.Put(strPlus); #endregion Console.ReadLine();
}
}
}
C# Type.GetConstructor() 根据构造函数参数获取实例对象(一)的更多相关文章
- SpringBoot 基于web应用开发(请求参数获取,静态资源,webjars)
SpringBoot 基于web应用开发 一.Lombok使用 1.导入依赖库 <dependency> <groupId>org.projectlombok</g ...
- hiero.ui获取实例名的方法
在hiero.ui中经常会通过hiero.ui.windowManager().windows()来获取当前QMainWindow中的QWidget子窗口,而这些子窗口是以实例对象的方式返回的,如果想 ...
- JS高级---实例对象和构造函数之间的关系
实例对象和构造函数之间的关系: 1. 实例对象是通过构造函数来创建的---创建的过程叫实例化 2. 如何判断对象是不是这个数据类型? 1) 通过构造器的方式 实例对象.构造器==构造函数 ...
- JS中new的自定义实现创建实例对象
我们都知道在JS中通常通过对象字面量和new关键字来创建对象,那么今天我就来给大家讲讲new是怎么创建实例对象的:首先创建一个构造函数: function Person(name,age){ this ...
- 对ES6中类class以及实例对象、原型对象、原型链之间关系的详细总结
1. 类 ES6 中新增加了类的概念,可以使用 class 关键字声明一个类,之后用这个类来实例化对象.即类的用途:实例化对象. // 创建一个Person类 class Person { } // ...
- 理解Python中的类对象、实例对象、属性、方法
class Animal(object): # 类对象 age = 0 # 公有类属性 __like = None # 私有类属性 def __init__(self): # 魔法方法 self.na ...
- promise核心技术 1 实例对象/函数对象
一个程序员要在看到代码的语法同时判断数据类型 知道语法是基础 基础才能延伸功能 //一行代码 a()[0]() // a() 首先推断出a是一个函数 //a()[0] 判断a函数的返回值是一个数组 ...
- JMeter学习-011-JMeter 后置处理器实例之 - 正则表达式提取器(三)多参数获取进阶引用篇
前两篇文章分表讲述了 后置处理器 - 正则表达式提取器概述及简单实例.多参数获取,相应博文敬请参阅 简单实例.多参数获取. 此文主要讲述如何引用正则表达式提取器获取的数据信息.其实,正则表达式提取器获 ...
- Java反射机制(获取Class对象的三种方式+获取Class中的构造函数进行对象的初始化+获取反射类的字段+获取反射类的一般方法)
反射技术其实就是动态加载一个指定的类,并获取该类中的所有内容.而且将字节码文件封装成对象,并将字节码文件中的内容都封装成对象,这样便于操作这些成员,简单来说:反射技术可以对一个类进行解剖,反射大大增强 ...
随机推荐
- 【并查集】bzoj2054 疯狂的馒头
因为只有最后被染上的颜色会造成影响,所以倒着处理,用并查集维护已经染色的区间的右端点,即fa[i]为i所在的已染色区间的右端点,这样可以保证O(n)的复杂度. #include<cstdio&g ...
- 【bitset】poj2443 Set Operation
模板题.S[i][j]表示i是否存在于第j个集合里.妈蛋poj差点打成poi(波兰无关)是不是没救了. #include<cstdio> #include<bitset> us ...
- python3开发进阶-Django框架起飞前的准备
阅读目录 安装 创建项目 运行 文件配置的说明 三个组件 一.安装(安装最新LTS版) Django官网下载页面 根据官方的图版本,我们下载1.11版本的,最好用! 有两种下载方式一种直接cmd里: ...
- BUG:Yii登录时 101 net::ERR_CONNECTION_RESET
Bug描述:YII web入口登录,无法登录一直等待,最终重定向 原因:设置的默认路由DefauRoute中的控制器中有错误,导致无法跳转找指定的路由规则 解决方案:这就多亏了SourceTree了, ...
- Go 测试单个方法/性能测试
Go 测试单个方法 gotest.go package mytest import ( "errors" ) func Division(a, b float64) (float6 ...
- CMD一键获取cpu信息
windows + R 输入cmd打开CMD 输入wmic cpu get Name 获取cpu名称-即物理cpu数 cpu get NumberOfCores获取cpu核心数 cpu get Num ...
- [TypeScript] Export public types from your library
If you're a library author, it's useful to expose your public types as interfaces, to allow your con ...
- Node.js meitulu图片批量下载爬虫1.04版
//====================================================== // https://www.meitulu.com图片批量下载Node.js爬虫1. ...
- bootstrap popover 如何在hover状态移动到弹出上不消失
bootstrap中的popover其实就是对tooltip做了一定升级,拥有了标题和内容 概要 使用的时候依赖第三方插件 依赖tooltip插件 必须初始化 title 和 content 可以在p ...
- B6:命令模式 Command
将一个请求封装成一个对象,从而可以用不同的请求对象对客户进行参数化,对请求排队或记录请求日志,以及支持可撤销的操作. 与状态模式和责任链模式的区别是,命令模式设定一次,统一执行 使用场景:1.可设计一 ...