简体   繁体   English

如何将当前实例传递给实例内部的FieldInfo.GetValue?

[英]How to pass the current instance to FieldInfo.GetValue inside the instance?

I'm making an abstract class that I need to validate fields in it's descendants. 我正在制作一个抽象类,需要验证其后代中的字段。 All the validated fields are marked by an attribute and are suppose to be checked for nulls or empty. 所有已验证的字段均由一个属性标记,并假定检查是否为空或为空。 To do that I get all the fields in the class: 为此,我获得了该类中的所有字段:

var fields = this.GetType().GetFields().Where(field => Attribute.IsDefined(field, typeof(MyAttribute))).ToList(); 

And then, for every FieldInfo I try to do this: 然后,对于每个FieldInfo,我都尝试这样做:

if (string.IsNullOrEmpty(field.GetValue(this).ToString()))
{
    // write down the name of the field
}

I get a System.NullReferenceException: object reference not set to an instance of an object . 我得到一个System.NullReferenceException:对象引用未设置为object的实例

I know I am suppose to pass the instance of a class to the GetValue method. 我知道我想将一个类的实例传递给GetValue方法。 But how can I pass the current instance (the one that's launching the logic)? 但是,如何传递当前实例(启动逻辑的实例)?

Or: Is there an other way of getting the field's value? 或:还有其他获取领域价值的方法吗?

The GetValue call is fine. GetValue调用很好。 The problem lies in the return value on which you're calling ToString . 问题出在调用ToString的返回值上。

If GetValue returns null , then ToString will be called on this null value, and this will throw the NullReferenceException . 如果GetValue返回null ,则将在此null值上调用ToString ,这将引发NullReferenceException

Do something like this instead: 做这样的事情:

var value = field.GetValue(this);
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
    // write down the name of the field
}

As Lucas says, the problem will be calling ToString() when you shouldn't. 正如卢卡斯所说,问题是您不应该调用ToString()时。 Presumably your attribute should only be applied to string fields anyway, so the simplest approach is just to cast the result to string . 大概您的属性无论如何都应该仅应用于字符串字段,因此最简单的方法就是将结果转换为string If that cast fails, it indicates a bigger bug (the attribute being applied incorrectly). 如果该强制转换失败,则表明存在较大的错误(属性应用不正确)。

if (string.IsNullOrEmpty((string) field.GetValue(this)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM