C#通过属性名称获取(读取)属性值的方法

木白
木白
发布时间:2026-10-13| 4人浏览过
原创

在C#开发中,若需根据属性名(字符串)动态读取对象的具体数值,标准做法是借助反射机制。本文将演示如何构建通用的取值方法,消除硬编码的分支判断。

核心原理与操作

在.NET中,反射允许我们在运行时检查类型信息。要获取指定名称属性的值,主要依赖 System.Reflection 命名空间下的两个关键动作:先通过属性名查找 PropertyInfo 实例,再执行取值操作。实质语句只有一句:

this.GetType().GetProperty(propertyName).GetValue(this, null);

其中:
1. this.GetType() 获取当前运行对象的类型描述符。
2. GetProperty(propertyName) 利用传入的字符串参数匹配公共(public)属性。
3. GetValue(this, null) 返回该属性在当前实例上的值;第二个参数用于索引器属性,普通属性传 null 即可。

实现方案对比

第1步:使用抽象基类实现通用方法

目的:创建一个可复用的父类,使所有继承它的子类都自动拥有“按名取值”的能力。

操作步骤:

  1. 定义一个抽象类 AbstractGetValue。
  2. 在该类中实现 GetValue(string propertyName) 方法,核心逻辑即上面提到的反射语句。
  3. 让具体业务类(如 Person, Demo)继承此类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PropertyNameGetPropertyValueDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Person ps = new Person();
            ps.Name = "CTZ";
            ps.Age = 21;
            Demo dm = new Demo();
            dm.Str = "String";
            dm.I = 1;

            // 输出结果: CTZ, 21, String, 1
            Console.WriteLine(ps.GetValue("Name"));
            Console.WriteLine(ps.GetValue("Age"));
            Console.WriteLine(dm.GetValue("Str"));
            Console.WriteLine(dm.GetValue("I"));
        }
    }

    abstract class AbstractGetValue
    {
        public object GetValue(string propertyName)
        {
            return this.GetType().GetProperty(propertyName).GetValue(this, null);
        }
    }

    class Person : AbstractGetValue 
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Demo : AbstractGetValue
    {
        public string Str { get; set; }
        public int I { get; set; }
    }
}

第2步:直接在类内部简化实现

目的:如果不需要复杂的层级管理,可直接将方法添加到单个类中,代码更精简。

操作步骤:

  1. 在目标类(例如 Person)中添加私有或公共方法。
  2. 复用相同的反射逻辑,无需额外继承链。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GetValue
{
    class Program
    {
        static void Main(string[] args)
        {
            Person ps = new Person();
            ps.Name = "CTZ";
            ps.Age = 21;

            // 输出结果: CTZ, 21
            Console.WriteLine(ps.GetValue("Name"));
            Console.WriteLine(ps.GetValue("Age"));
        }
    }

    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public object GetValue(string propertyName)
        {
            return this.GetType().GetProperty(propertyName).GetValue(this, null);
        }
    }
}

注意事项与排错

缺失属性异常: GetProperty` 如果未找到对应名称的属性(区分大小写),将返回 null。随后调用 .GetValue` 时会抛出 NullReferenceException。建议在开发环境中增加判空保护。

性能考量: 反射属于运行时行为,相比直接属性访问开销较大。如果需要在高频循环中大量调用,应考虑将 GetProperty` 的结果进行缓存(例如使用字典存储委托),或者结合表达式树(Expression Trees)生成编译后的委托以提升性能。

以上就是C#通过属性名称获取属性值的详细内容,更多关于C#反射读取属性的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。