c# - 给定属性名称,是否有返回对象属性值的 C# 函数?
问题描述
假设我有一个像
class Test {
public Test() {
Name = "Hello";
}
public string Name { get; set; }
}
我想要一个函数,当给定一个对象和一个字符串时,它返回名称为字符串的对象的属性值。例如,
Test myTest = new Test();
string myName = f(myTest, "Name"); // myName == "Hello"
这可能吗?有没有这样的功能?
解决方案
你在反思之后。
Test myTest = new Test();
string myName = (string)myTest.GetType().GetProperty("Name")?.GetValue(myTest); // myName == "Hello"
推荐阅读
- javascript - 在 react 中创建一个模块,将生成一个包含 100 个用户的数组
- reactjs - 验证不适用于 React Datepicker 和 Formik
- c# - 如何处理客户端/服务器应用程序代码中的网络数据包?
- c++ - 是
包括在 ? - ubuntu - 尝试启动 Ubuntu gui 时重启出错
- javascript - 如何让选择器在 React 中的琐事游戏中工作?
- cython - cdef函数下可以引用Python对象吗?
- python - 用另一个 numpy 数组的值逐行替换 numpy 数组
- reactjs - 在 React 中使用 useContext 并没有给我期望的数据
- sql-server - SQL Server 根据当前日期使用 Order By 对数据进行排序