C#---反射ConstructorInfo
来源:互联网 发布:皇室战争mac模拟器 编辑:程序博客网 时间:2024/05/17 22:14
先上例子
using System;using System.Reflection;namespace HGFramwork{ class ConstructorTest { public int number = 10; public string name = "Money"; public ConstructorTest() { Console.WriteLine("Null parammeter"); } private ConstructorTest(int _number) { Console.WriteLine("The number is : " + _number); } public ConstructorTest(int _numaber, string _name) { number = _numaber; name = _name; Console.WriteLine("Two parammeters"); } public void FnDebug() { Console.WriteLine("Goodbye World"); } private void FnDebugParam(string _numa) { Console.WriteLine(_numa + " Say : Goodbye World"); } } class Program { static void Main(string[] args) { //按照所选择的参数,返回这个类里面所有符合要求构造函数 //如果是私有的话,参数可以选择BindingFlags.NonPublic | BindingFlags.Instance ConstructorInfo[] ctor = typeof(ConstructorTest).GetConstructors(); //用Lamber表达式,查找含有两个参数的构造函数 ConstructorInfo info = Array.Find(ctor, c => c.GetParameters().Length == 2); if (info != null) { //调用构造函数,传入两个参数,返回一个该类的实例 ConstructorTest test = info.Invoke(new object[] {100,"Tom"}) as ConstructorTest; Console.WriteLine("name is : " + test.name + "\n" + "number is: " +test.number); //获取该类里面指定函数信息,这里FnDebugParam是一个私有方法,所以传入参数 BindingFlags.NonPublic | BindingFlags.Instance MethodInfo method = typeof(ConstructorTest).GetMethod("FnDebugParam",BindingFlags.NonPublic | BindingFlags.Instance); if (method!=null) { //调用该方法,并传入该方法所需的参数 method.Invoke(test, new object[] { "Jimy" }); } else { Console.WriteLine("The method is null"); } //也是获取方法的,不过这里获取的是该类所有公有方法 MethodInfo[] methods = typeof(ConstructorTest).GetMethods(); //找到所需要的指定方法 MethodInfo methodInfo = Array.Find(methods, m => m.Name.Equals("FnDebug")); if (methodInfo != null) { //实现方法,该方法没有参数,传入null methodInfo.Invoke(test,null); } } else { Console.WriteLine("Is not hava cur object"); } Console.ReadKey(); } } //输出信息: //Two parammeters //name is : Tom //number is : 100 //Jimy Say : Goodbye World //Goodbye World}
这里只稍微写了下获取方法的,还有一些获取字段之类的,大同小异。具体的可以去MSDN上查找相关信息。
0 0
- C#---反射ConstructorInfo
- System.Reflection.ConstructorInfo
- C#--反射
- c++“反射”?
- C#---反射
- C#--反射
- [C#] 白话C#:反射
- C#反射实例
- C#反射实例
- C++模拟反射
- [C#] 反射的用法
- Reflection(反射)[C#]
- C#反射实例
- 反射(c#)
- Objective-C的反射
- Objective-c 反射
- Objective-C的反射
- Object c 反射
- 微信API实例(OKHttp+PullToRefreshListView+WebView综合应用)
- Ant Colony Optimization
- struts2(二) 表单参数自动封装和参数类型自动转换
- Android ToolBar的使用
- 我看百度的问题
- C#---反射ConstructorInfo
- Spring MVC入门2——一个简单例子
- Opencv2.4.13 与Visual Studio2013 环境搭建配置
- 【转】如何管理好新接手的团队
- 平衡二叉树的判断-->后序遍历
- Docker
- oracle通过impdp导入不同表用户、不同表空间的数据
- 浅析Content Negotation在Nancy的实现和使用
- C++指针做函数参数传递的是指针的值!