C# 反射(Reflection)使用讲解之 - 调用普通、私有方法、静态方法、重载方法(二)
最近学习C#基础,简单记录一下C#中如何使用反射创建对象,并调用方法。
使用反射必须添加System.Reflection引用。
Assembly assembly = Assembly.LoadFrom("DB.MySql.dll");
Type type = assembly.GetType("DB.MySql.TestClass");
object testClass = Activator.CreateInstance(type);
//一般方法调用
MethodInfo methodInfo1 = type.GetMethod("Test1");
methodInfo1.Invoke(testClass, new object[] { "方法参数" });
//重载方法调用
MethodInfo methodInfo3 = type.GetMethod("Test2", new Type[] { });
methodInfo3.Invoke(testClass, null);
MethodInfo methodInfo2 = type.GetMethod("Test2", new Type[] { typeof(string) });//指定参数类型及个数
methodInfo2.Invoke(testClass, new object[] { "方法参数" });
//静态方法调用
//方式1
MethodInfo methodInfo4 = type.GetMethod("Test3");
methodInfo4.Invoke(testClass, new object[] { "方法参数" });
//方式2
MethodInfo methodInfo5 = type.GetMethod("Test3");
methodInfo5.Invoke(null, new object[] { "方法参数" });
//调用私有方法
MethodInfo methodInfo6 = type.GetMethod("Test4",BindingFlags.Instance|BindingFlags.NonPublic);
methodInfo6.Invoke(testClass, new object[] { "方法参数" });
方法类代码如下:
namespace DB.MySql
{
public class TestClass
{
public TestClass() {
Console.WriteLine($"这是{this.GetType()}无参构造方法");
}
public void Test1(string name)
{
Console.WriteLine($"这是{this.GetType()}Test1方法,类型为{name.GetType()}");
}
public void Test2()
{
Console.WriteLine($"这是{this.GetType()}Test2重载无参方法");
}
public void Test2(string name)
{
Console.WriteLine($"这是{this.GetType()}Test1重载1个参数方法,类型为{name.GetType()}");
}
public static void Test3(string name)
{
Console.WriteLine($"这是{typeof(TestClass)}Test3静态方法,类型为{name.GetType()}");
}
private void Test4(string name)
{
Console.WriteLine($"这是{typeof(TestClass)}Test3静态方法,类型为{name.GetType()}");
}
}
}
运行结果:

猜您可能还喜欢
评论列表
发表评论
文章分类
文章归档
- 2025年3月 (1)
- 2024年6月 (2)
- 2024年5月 (2)
- 2024年4月 (4)
- 2024年3月 (30)
- 2024年1月 (4)
- 2023年12月 (2)
- 2023年11月 (4)
- 2023年10月 (4)
- 2023年9月 (6)
- 2023年3月 (2)
- 2023年2月 (1)
- 2023年1月 (1)
- 2022年12月 (1)
- 2022年9月 (21)
- 2022年8月 (10)
- 2022年7月 (3)
- 2022年4月 (1)
- 2022年3月 (13)
- 2021年8月 (1)
- 2021年3月 (1)
- 2020年12月 (42)
- 2020年11月 (7)
- 2020年10月 (5)
- 2020年8月 (1)
- 2020年6月 (1)
- 2020年3月 (2)
- 2019年12月 (8)
- 2019年11月 (3)
- 2019年9月 (1)
- 2019年4月 (1)
- 2019年3月 (6)
- 2019年2月 (1)
- 2018年7月 (7)
阅读排行
- 1.asp.net mvc内微信pc端、H5、JsApi支付方式总结(5920)
- 2.Windows 10休眠文件更改存储位置(4025)
- 3.各大搜索网站网站收录提交入口地址(3507)
- 4.windows 10安装myeclipse 10破解补丁cracker.jar、run.bat闪退解决办法(3483)
- 5.ECharts仪表盘实例及参数使用详解(3466)
- 6.华为鸿蒙系统清除微信浏览器缓存方法(3262)
- 7.HTML5 WebSocket与C#建立Socket连接实现代码(3222)
- 8.CERT_HAS_EXPIRED错误如何解决(3023)
- 9.Js异步async、await关键字详细介绍(lambda表达式中使用async和await关键字)(2673)
- 10.HBuilder编辑器格式化代码(2433)
