用反射得到领域

syn*_*cis 7 c# reflection class

我想得到所有具有空值的字段,但我甚至得到任何字段:

  [Serializable()]
public class BaseClass
{
    [OnDeserialized()]
    internal void OnDeserializedMethod(StreamingContext context)
    {
        FixNullString(this);
    }

    public void FixNullString(object type)
    {
        try
        {
            var properties = type.GetType().GetFields();


            foreach (var property in from property in properties
                                     let oldValue = property.GetValue(type)
                                     where oldValue == null
                                     select property)
            {
                property.SetValue(type, GetDefaultValue(property));
            }
        }
        catch (Exception)
        {

        }
    }

    public object GetDefaultValue(System.Reflection.FieldInfo value)
    {
        try
        {
            if (value.FieldType == typeof(string))
                return "";

            if (value.FieldType == typeof(bool))
                return false;

            if (value.FieldType == typeof(int))
                return 0;

            if (value.FieldType == typeof(decimal))
                return 0;

            if (value.FieldType == typeof(DateTime))
                return new DateTime();
        }
        catch (Exception)
        {

        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一堂课:

    [Serializable()]
public class Settings : BaseClass
{
    public bool Value1 { get; set; }
    public bool Value2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是当我来的时候

 var properties = type.GetType().GetFields();
Run Code Online (Sandbox Code Playgroud)

然后我得到0个字段,它应该找到2个字段.

是否使用type.getType().GetFields()错误?或者我是否在错误的班级中向基地派遣?

Pat*_*tko 21

Type.GetFields方法返回所有公共字段.编译器为您自动生成的字段是私有的,因此您需要指定正确的字段BindingFlags.

type.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
Run Code Online (Sandbox Code Playgroud)