当前位置: 首页 > article >正文

Reflect中MethodInfo使用方法

ReflectMethodInfo使用方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MethodInfoInvokeDemo
{
public class ReflectTest
{
public void MethodWithNoParaNoReturn()
{
Console.WriteLine("不带参数且不返回值的方法");
}

public string MethodWithNoPara()
{
Console.WriteLine("不带参数且有返回值的方法");
return "MethodWithNoPara";
}

public string Method1(string str)
{
Console.WriteLine("带参数且有返回值的方法");
return str;
}

public string Method2(string str, int index)
{
Console.WriteLine("带参数且有返回值的方法");
return str + index.ToString();
}

public string Method3(string str, out string outStr)
{
outStr = "bbbb";
Console.WriteLine("带参数且有返回值的方法");
return str;
}

public static string StaticMethod()
{
Console.WriteLine("静态方法");
return "cccc";
}
}

class Program
{
static void Main(string[] args)
{
Type type = typeof(ReflectTest);
object reflectTest = Activator.CreateInstance(type);

//不带参数且不返回值的方法的调用
MethodInfo methodInfo = type.GetMethod("MethodWithNoParaNoReturn");
methodInfo.Invoke(reflectTest, null);

Console.WriteLine();

//不带参数且有返回值的方法的调用
methodInfo = type.GetMethod("MethodWithNoPara");
Console.WriteLine(methodInfo.Invoke(reflectTest, null).ToString());

Console.WriteLine();

//带参数且有返回值的方法的调用
methodInfo = type.GetMethod("Method1", new Type[]{typeof(string)});
Console.WriteLine(methodInfo.Invoke(reflectTest, new object[]{"测试"}).ToString());

Console.WriteLine();

//带多个参数且有返回值的方法的调用
methodInfo = type.GetMethod("Method2", new Type[] { typeof(string), typeof(int) });
Console.WriteLine(methodInfo.Invoke(reflectTest, new object[] { "测试", 100 }).ToString());

//Console.WriteLine();

//methodInfo = type.GetMethod("Method3", new Type[] { typeof(string), typeof(string) });
//string outStr = "";
//Console.WriteLine(methodInfo.Invoke(reflectTest, new object[] { "测试", outStr }).ToString());

Console.WriteLine();

//静态方法的调用
methodInfo = type.GetMethod("StaticMethod"); 
Console.WriteLine(methodInfo.Invoke(null, null).ToString());

Console.ReadKey();
}
}
}

 

http://www.lryc.cn/news/2413829.html

相关文章:

  • MyEclipse 8.0 M1 下载 (Standard and Pro Editions)
  • 本地连接的ip地址 子网掩码 默认网关 还有dns服务器地址怎么设置? (转自网易博客)
  • OA项目之我的审批(查询会议签字)
  • nodejs 使用async进行BT吧最新电影数据爬取
  • FLASH常见问题
  • C/C++《计算思维综合实践I》参考选题(84题)[2024-05-22]
  • 个人面试总结暨2020年终总结
  • 聊一聊go的单元测试(goconvey、gomonkey、gomock、ginkgo)
  • 乐Pad A1拆机全程
  • 小周恋爱日记网站
  • 恐龙机器人钢索恐龙形态_机器恐龙铁渣2.0:P1S的钢索终于有伴了
  • 如何查找和注册已备案过期域名
  • 【纯转】Div+CSS经典速成教程。
  • 一文实现nnUNet v2 分割肾脏肿瘤数据集KiTS19
  • win篇--winserver2008R2系统自动更新报错:代码:80092004
  • 火狐与IE兼容性总结(待整理,代码有点乱)
  • MDK常用快捷键和操作
  • 企业竞争竞争情报系统的流程整合
  • 天天酷跑刷钻石辅助下载 最新无异常攻略
  • vs2005 创建动态库及其调用方法
  • CDLINUX U盘安装教程
  • 图像处理入门教程
  • 我的百度blog
  • ctfshow web176-? 的waf(方便对题目差异)
  • 获取屏幕宽度_手机屏幕的那些门道,一文看懂!
  • 未来三年的移动互联网创业----创新工场创始合伙人汪华 在移动开发者大会上的演讲
  • 网页三剑客的一些序列号
  • vue下实现类似android或者ios通讯录(银行选择)-网页版
  • 解决横竖屏样式错乱问题
  • 我们注意到您的计算机目前处于离线状态_如何将您的计算机添加到Pekka网络