简体   繁体   中英

How can I get around casting to the FieldInfo?

How can i get around casting to FieldInfo? With the code below it throws InvalidCastException when derived class has ie bool variable. The problem is that it also returns null as a value of field. (everything happens in last 5 lines, but i paste more for context)

    {
        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 . 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.

[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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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