[英]Avoid null reference warnings when dynamically accessing properties of object using reflection in C#
我正在尝试使用反射动态访问 object 的属性:
class Program
{
private class MyClass
{
public int prop1 { get; set; } = 1;
public int prop2 { get; set; } = 2;
}
public static void Main()
{
var obj = new MyClass();
var propList = new List<string> { "prop1", "prop2"};
foreach (string propString in propList)
{
var prop = obj.GetType().GetProperty(propString);
// I get a compiler warning here: "Dereference of a possibly null reference."
Console.WriteLine((int)prop.GetValue(obj));
}
}
}
我想以适当的方式防止“空引用”警告。
我尝试添加一个if (prop == null) return;
在Console.WriteLine
之前检查,但这并不能解决问题。 相反,它将警告变为“拆箱可能的 null 值”。
有没有办法强制 propList 中的字符串是 MyClass 中的属性名称? 在那种情况下,我会很乐意用 a 使警告静音。 因为我知道该财产将永远存在,所以在我看来这将是理想的。 因为那样我在创建列表时会遇到编译器错误。
看起来它不仅仅是prop
可能是 null,还有prop.GetValue(obj)
返回的值。
尝试
var prop = obj.GetType().GetProperty(propString);
if (prop == null) return;
var o = prop.GetValue(obj);
if (o == null) return;
Console.WriteLine((int)o);
或同等学历。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.