C# 动态获取属性值

如何利用反射实现对类属性的动态操作?

首先,自定义一个类:

/// <summary>
/// 自定义类
/// </summary>
public class MyClass
{
    public string Name { get; set; }

    public string Age{ get; set; }
}

1.1 动态获取

/// <summary>
/// 获取属性值
/// </summary>
/// <returns></returns>
public static string GetMyClassVal(string propertyKey)
{
    MyClass entity = new MyClass();
    //获取类型
    Type type = entity.GetType();
    //获取属性
    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyKey);
    //获取属性值
    string val = (string)propertyInfo.GetValue(entity, null);

    return val;
}

1.2 动态赋值

/// <summary>
/// 设置属性值
/// </summary>
/// <returns></returns>
public static string SetMyClassVal(string propertyKey, string val)
{
    MyClass entity = new MyClass();
    //获取类型
    Type type = entity.GetType();
    //获取属性
    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyKey);
    //设置属性值
    propertyInfo.SetValue(entity, val, null);

    string newVal = (string)propertyInfo.GetValue(entity, null);
    return newVal;
}

1.3 动态存取Plus版

通过上面两节,我们实现了对属性的动态获取/赋值。

接下来,有意思的来了:假设代码中存在多个类型,比如MyClassMyClassExtendMyClassPlus,都要进行动态存取。

为了更好偷懒,该怎么写呢?

话不多说,coding——

/// <summary>
/// 新类
/// </summary>
public class MyClassExtend
{
    public string Address { get; set; }
}

public class MyClassPlus
{
    public string HelloWorld { get; set; }
}

/// <summary>
/// 获取属性值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="myClass"></param>
/// <param name="propertyKey"></param>
/// <returns></returns>
public static string GetClassVal<T>(T myClass, string propertyKey)
{
    Type type = myClass.GetType();
    System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyKey);
    string val = (string)propertyInfo.GetValue(myClass, null);

    return val;
}

/// <summary>
/// 调用
/// </summary>
public static void Demo()
{
    var nameVal = GetClassVal(new MyClass(), "Name");
    var adrsVal = GetClassVal(new MyClassExtend(), "Address");
    var helloVal = GetClassVal(new MyClassPlus(), "HelloWorld");
}

本文作者:暴躁老砚

本文链接:https://www.cnblogs.com/Yan3399/p/18040705

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   暴躁老砚  阅读(254)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.