C#使用反射机制实现延迟绑定
作者:Darren 时间:2021-06-13 22:22:42
反射允许我们在编译期或运行时获取程序集的元数据,通过反射可以做到:
● 创建类型的实例
● 触发方法
● 获取属性、字段信息
● 延迟绑定
......
如果在编译期使用反射,可通过如下2种方式获取程序集Type类型:
1、Type类的静态方法
Type type = Type.GetType("somenamespace.someclass");
2、通过typeof
Type type = typeof(someclass);
如果在运行时使用反射,通过运行时的Assembly实例方法获取Type类型:
Type type = asm.GetType("somenamespace.someclass");
获取反射信息
有这样的一个类:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public float Score { get; set; }
public Student()
{
this.Id = -1;
this.Name = string.Empty;
this.Score = 0;
}
public Student(int id, string name, float score)
{
this.Id = id;
this.Name = name;
this.Score = score;
}
public string DisplayName(string name)
{
return string.Format("学生姓名:{0}", name);
}
public void ShowScore()
{
Console.WriteLine("学生分数是:" + this.Score);
}
}
通过如下获取反射信息:
static void Main(string[] args)
{
Type type = Type.GetType("ConsoleApplication1.Student");
//Type type = typeof (Student);
Console.WriteLine(type.FullName);
Console.WriteLine(type.Namespace);
Console.WriteLine(type.Name);
//获取属性
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
Console.WriteLine(prop.Name);
}
//获取方法
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
Console.WriteLine(method.ReturnType.Name);
Console.WriteLine(method.Name);
}
Console.ReadKey();
}
延迟绑定
在通常情况下,为对象实例赋值是发生在编译期,如下:
Student stu = new Student();
stu.Name = "somename";
而"延迟绑定",为对象实例赋值或调用其方法是发生在运行时,需要获取在运行时的程序集、Type类型、方法、属性等。
//获取运行时的程序集
Assembly asm = Assembly.GetExecutingAssembly();
//获取运行时的Type类型
Type type = asm.GetType("ConsoleApplication1.Student");
//获取运行时的对象实例
object stu = Activator.CreateInstance(type);
//获取运行时指定方法
MethodInfo method = type.GetMethod("DisplayName");
object[] parameters = new object[1];
parameters[0] = "Darren";
//触发运行时的方法
string result = (string)method.Invoke(stu, parameters);
Console.WriteLine(result);
Console.ReadKey();
来源:https://www.cnblogs.com/darrenji/p/3817999.html
标签:C#,反射,延迟,绑定
0
投稿
猜你喜欢
c# 实现KMP算法的示例代码
2023-12-02 06:35:19
Java可变个数形参的方法实例代码
2023-01-15 18:35:56
java9版本特性资源自动关闭的语法增强
2023-10-30 23:35:24
JavaWeb项目部署到服务器详细步骤详解
2023-11-29 11:15:20
C# 使用HttpClient模拟请求的案例
2023-10-16 18:20:14
android 实现类似微信缓存和即时更新好友头像示例
2023-12-04 20:47:41
使用Java实现串口通信
2023-02-13 05:45:02
spring整合redis缓存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用
2022-04-25 01:46:14
Android中获取资源 id 及资源 id 的动态获取
2023-06-30 04:38:06
浅谈Java方法调用的优先级问题
2023-07-01 13:40:08
Unity2D实现游戏回旋镖
2022-07-16 07:13:50
Android显示网络图片实例
2022-11-02 14:13:31
Android如何通过组合的方式自定义View
2022-11-01 04:33:46
C# 获取 PC 序列号的方法示例
2022-11-19 01:40:57
C#读取word中表格数据的方法实现
2023-09-12 22:54:53
基于WPF实现简单的文件夹比较工具
2023-11-15 16:08:34
C#自定义缓存封装类实例
2023-10-15 09:24:27
idea创建JAVA Class时自动生成头部文档注释的方法
2023-07-10 18:53:07
使用Jacoco获取 Java 程序的代码执行覆盖率的步骤详解
2022-07-22 00:25:13
java 线程方法join简单用法实例总结
2022-10-26 19:27:38