C# 快速简单反射操作

前言

我之前写过一篇博客,是关于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 "返回参数";
    }
}

运行结果

在这里插入图片描述

这里只将了简单的公有数据,私有属性和静态属性也差不多,这里我就不展开说明了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值