首页 > 解决方案 > 给定属性名称,是否有返回对象属性值的 C# 函数?

问题描述

假设我有一个像

class Test {
  public Test() {
    Name = "Hello";
  }

  public string Name { get; set; }
}

我想要一个函数,当给定一个对象和一个字符串时,它返回名称为字符串的对象的属性值。例如,

Test myTest = new Test();
string myName = f(myTest, "Name"); // myName == "Hello"

这可能吗?有没有这样的功能?

标签: c#

解决方案


你在反思之后。

Test myTest = new Test();

string myName = (string)myTest.GetType().GetProperty("Name")?.GetValue(myTest); // myName == "Hello"

推荐阅读