简体   繁体   English

如何绕过投射到 FieldInfo?

[英]How can I get around casting to the FieldInfo?

How can i get around casting to FieldInfo?我怎样才能绕过投射到 FieldInfo? With the code below it throws InvalidCastException when derived class has ie bool variable.使用下面的代码,当派生的 class 具有 ie bool 变量时,它会抛出 InvalidCastException。 The problem is that it also returns null as a value of field.问题是它还返回 null 作为字段值。 (everything happens in last 5 lines, but i paste more for context) (一切都发生在最后 5 行,但我粘贴更多内容)

    {
        string paramsData = ".";
        if (param == null)
        {
            return paramsData;
        }
        BindingFlags bindingFlags = BindingFlags.Public |
                        BindingFlags.NonPublic |
                        BindingFlags.Instance |
                        BindingFlags.Static;
        FieldInfo[] paramFields = param.GetType().GetFields(bindingFlags);

        foreach (FieldInfo field in paramFields)
        {
            paramsData += field.Name;
            Param child = (Param)field.GetValue(param);
            paramsData += GetParamDataInChildren(child);
        }
        return paramsData;
    }

It is difficult to know what you are trying to achieve, but it looks like you should be checking the type of your field before calling GetValue .很难知道您要实现什么目标,但看起来您应该在调用GetValue之前检查字段的类型。 For example:例如:

if (field.FieldType == typeof(Param))
{
    Param child = (Param)field.GetValue(param);
    paramsData += GetParamDataInChildren(child);
}

Note that child could still be null in this case, and you should check for that if the subsequent function doesn't handle it.请注意,在这种情况下, child仍然可能是 null,如果后续的 function 没有处理它,您应该检查它。

[EDIT] If you are trying to recursively get all the fields, regardless of type, you should make your recursive function take Object rather than Param and then you won't need to cast to Param as GetValue returns Object . [编辑]如果您GetValue ObjectParam所有Param ,无论类型Object

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

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