[英]How to pass the current instance to FieldInfo.GetValue inside the instance?
我正在制作一个抽象类,需要验证其后代中的字段。 所有已验证的字段均由一个属性标记,并假定检查是否为空或为空。 为此,我获得了该类中的所有字段:
var fields = this.GetType().GetFields().Where(field => Attribute.IsDefined(field, typeof(MyAttribute))).ToList();
然后,对于每个FieldInfo,我都尝试这样做:
if (string.IsNullOrEmpty(field.GetValue(this).ToString()))
{
// write down the name of the field
}
我得到一个System.NullReferenceException:对象引用未设置为object的实例 。
我知道我想将一个类的实例传递给GetValue方法。 但是,如何传递当前实例(启动逻辑的实例)?
或:还有其他获取领域价值的方法吗?
GetValue
调用很好。 问题出在调用ToString
的返回值上。
如果GetValue
返回null
,则将在此null
值上调用ToString
,这将引发NullReferenceException
。
做这样的事情:
var value = field.GetValue(this);
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
// write down the name of the field
}
正如卢卡斯所说,问题是您不应该调用ToString()
时。 大概您的属性无论如何都应该仅应用于字符串字段,因此最简单的方法就是将结果转换为string
。 如果该强制转换失败,则表明存在较大的错误(属性应用不正确)。
if (string.IsNullOrEmpty((string) field.GetValue(this)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.