使用反射调用GetProperty()返回null的问题排查求助
解决反射获取属性返回null的问题及批量设置属性方案
先看你代码里的两个致命错误
- 拼写错误:
GetType().GetPropterty(...)里的方法名拼错了,应该是GetProperty(少了一个'e'),这个低级错误直接会导致调用错误方法,返回null。 - 参数传错:你传入的
L1Value是属性的当前实例值,而GetProperty需要的是属性名称的字符串。比如要获取L1Value这个属性,应该传"L1Value"而不是变量L1Value。
修正后的单个属性获取示例
public void MethodToGetProperty() { // 注意方法名拼写和参数是字符串常量 var result = GetType().GetProperty("L1Value"); }
针对批量设置属性的优化方案
既然你要批量处理5个属性,直接循环属性名列表即可,下面是完整的批量设置示例:
public class MyClass { public string? L1Value { get; set; } public string? L2Value { get; set; } public string? L3Value { get; set; } public string? L4Value { get; set; } public string? L5Value { get; set; } public void BatchSetProperties() { // 定义属性名列表和对应的值(这里可以根据你的业务逻辑生成值) var propertyValues = new Dictionary<string, string> { {"L1Value", "值1"}, {"L2Value", "值2"}, {"L3Value", "值3"}, {"L4Value", "值4"}, {"L5Value", "值5"} }; var type = GetType(); foreach (var kvp in propertyValues) { // 获取属性,显式指定BindingFlags确保匹配公共实例属性 var property = type.GetProperty(kvp.Key, BindingFlags.Public | BindingFlags.Instance); if (property != null && property.CanWrite) { // 设置属性值 property.SetValue(this, kvp.Value); } } } }
其他可能的排查点(如果还有问题的话)
- 大小写问题:默认
GetProperty区分大小写,如果你的属性名和传入的字符串大小写不匹配,会返回null。可以用重载忽略大小写:var property = type.GetProperty(kvp.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); - 确认属性的可写性:确保属性有
set访问器(你的示例里都有,但如果是只读属性,CanWrite会是false,无法设置值)。
内容的提问来源于stack exchange,提问作者USMC6072
相关产品推荐
相关产品推荐

