C# 快速简单反射操作
文章目录
- 前言
- 新反射使用
- BindingFlags
- 以公有属性使用举例
- 运行结果
前言
我之前写过一篇博客,是关于C# 反射的,我那时候使用的C# 反射写起来还是比较麻烦,需要获取Properies,再遍历Property,再找到对应Property,再使用。特别的麻烦。
C# 反射+泛型总结和应用
后来我在网上找了一下,找到了个视频,挺好的。
C#基础教程 Reflection应用,简单使用反射,打破常规!
新反射使用
BindingFlags
BindingFlags 是可以简化反射类型的参数。使用举例如下
//Public:公有,Instance:实例
BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
反射会得到三大类:
- 静态|非静态
- 公有|私有
- 属性|字段|方法
以公有属性使用举例
static async Task Main(string[] args){BindTest bindTest = new BindTest();Type type = bindTest.GetType();BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;FieldInfo? fieldInfo = type.GetField("Field",bindingFlags);Console.WriteLine(fieldInfo?.GetValue(bindTest));fieldInfo?.SetValue(bindTest, "新字段值");Console.WriteLine(fieldInfo?.GetValue(bindTest));Console.WriteLine("******************");PropertyInfo? propertyInfo = type.GetProperty("Property", bindingFlags);Console.WriteLine(propertyInfo?.GetValue(bindTest));propertyInfo?.SetValue(bindTest, "新属性值");Console.WriteLine(propertyInfo?.GetValue(bindTest));Console.WriteLine("******************");MethodInfo? method1 = type.GetMethod("Method", bindingFlags);method1?.Invoke(bindTest, null);MethodInfo? method2 = type.GetMethod("Method2", bindingFlags);method2?.Invoke(bindTest, new object[]{"测试参数"});MethodInfo? method3 = type.GetMethod("Method3", bindingFlags);var res = method3?.Invoke(bindTest, null);Console.WriteLine(res);Console.WriteLine("******************");Console.WriteLine("运行完成!");}}public class BindTest
{public string Field = "公有字段";public string Property { get; set; } = "公有属性";public void Method(){Console.WriteLine("公有函数");}public void Method2(string str){Console.WriteLine($"公有参数函数,{str}");}public string Method3(){return "返回参数";}
}
运行结果
这里只将了简单的公有数据,私有属性和静态属性也差不多,这里我就不展开说明了。