高端品牌网站建设兴田德润在哪儿,怎么做旅游网站,嵌入式软件开发岗位职责,hexo与wordpress区别文章目录 前言新反射使用BindingFlags以公有属性使用举例运行结果 前言
我之前写过一篇博客#xff0c;是关于C# 反射的#xff0c;我那时候使用的C# 反射写起来还是比较麻烦#xff0c;需要获取Properies,再遍历Property#xff0c;再找到对应Property#xff0c;再使用… 文章目录 前言新反射使用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 返回参数;}
}运行结果 这里只将了简单的公有数据私有属性和静态属性也差不多这里我就不展开说明了。