C# 无反射访问类属性:字典、动态类型、委托
在C#中,要通过字符串访问一个类的属性值,不使用反射可以通过以下几种方式实现:
- 使用字典/哈希表存储属性名和属性值的映射关系:
public class MyClass
{
public int MyProperty { get; set; }
}
Dictionary<string, object> propertyMap = new Dictionary<string, object>();
MyClass myObject = new MyClass();
myObject.MyProperty = 10;
// 存储属性名和属性值的映射关系
propertyMap['MyProperty'] = myObject.MyProperty;
// 通过属性名获取属性值
int propertyValue = (int)propertyMap['MyProperty'];
- 使用动态类型:
public class MyClass
{
public int MyProperty { get; set; }
}
dynamic myObject = new MyClass();
myObject.MyProperty = 10;
// 通过字符串访问属性值
int propertyValue = myObject.MyProperty;
- 使用委托:
public class MyClass
{
public int MyProperty { get; set; }
}
Func<MyClass, int> getProperty = x => x.MyProperty;
MyClass myObject = new MyClass();
myObject.MyProperty = 10;
// 通过委托访问属性值
int propertyValue = getProperty(myObject);
请根据具体的需求选择适合的方法。
原文地址: https://www.cveoy.top/t/topic/pV7n 著作权归作者所有。请勿转载和采集!