c# - 用反射清理我的代码

标签 c# serialization reflection

我想使用反射循环遍历我的 Car 类,以删除所有空值并将其替换为更好的值,例如 string = ""。

    [Serializable()]
public class Car
{
    public string model;
    public int year;
    public List<Owner> owner;
}

[Serializable()]
public class Owner
{
    public string firstName;
    public string lastName;
}

到目前为止我已经做到了

   public void LoopEverythingAndFix(object type)
    {
        var prop = type.GetType().GetFields();

        foreach (var fieldInfo in prop)
        {
            if (GetType(fieldInfo))
            {
                var value = fieldInfo.GetValue(type);

                if (value == null)
                    fieldInfo.SetValue(type, GetDefaultValue(fieldInfo));
            }
            else
            {
                LoopEverythingAndFix(fieldInfo);
            }
        }
    }
    public bool GetType(System.Reflection.FieldInfo fieldInfo)
    {
        if (fieldInfo.FieldType == typeof(string))
            return true;

        if (fieldInfo.FieldType == typeof(bool))
            return true;

        if (fieldInfo.FieldType == typeof(int))
            return true;

        if (fieldInfo.FieldType == typeof(decimal))
            return true;

        return false;
    }

GetType 方法用于了解当前字段是否为“owner”类之类的类,或者是否为“int/string”之类的值/引用字段,以及是否为“owner”类型然后我想循环它并修复这些属性。

问题是当它在汽车类中找到“所有者”并执行时:

 LoopEverythingAndFix(fieldInfo);

这就是问题所在,因为我将 fieldInfo 发送到方法 LoopEverythingAndFix ,当它返回循环时,它在 type.GetType 处获取 0 个字段().GetFields()。这是一个列表,我想循环列表项并将它们发送到 LoopEverythingAndFix 方法

最佳答案

您尝试在反射类型 FieldInfo 上调用 LoopEverythingAndFix,而不是您要修复的实际对象。

要修复,请替换此:

LoopEverythingAndFix(fieldInfo);

这样:

LoopEverythingAndFix(fieldInfo.GetValue(type));

关于c# - 用反射清理我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6386808/

相关文章:

java - 序列化 : (was java. lang.ArrayIndexOutOfBoundsException 时出现 JsonMappingException)

javascript - 在 Javascript 的表单序列化上只获取选定的值

c# - 从代码中获取 dll 引用的项目名称

c# - .netcore PUT 方法 405 方法不允许

c# 使用 HttpWebRequest 登录

c# - 读取 NetworkStream 不会推进流

C# WebBrowser 控件不应用 css

ios - 如何在应用程序 session 之间维护对象?

c# - 按任何属性对列表进行排序的更好方法

java - 是否可以在运行时从 java 对象中删除属性?