get fields with reflection

前端 未结 3 1868
忘掉有多难
忘掉有多难 2020-12-16 03:51

I want to get all fields that have null values but i aint even getting any fields:

  [Serializable()]
public class BaseClass
{
    [OnDeserialized()]
    int         


        
3条回答
  •  一个人的身影
    2020-12-16 04:53

    The fields generated by the compiler corresponding to properties of your class have the CompilerGenerated attribute. Also the compiler will generate get and set methods for handling these fields, depending on the declaration of your property.

    From CompilerGeneratedAttribute MSDN documentation:

    Distinguishes a compiler-generated element from a user-generated element. This class cannot be inherited.

    The name of these fields have the format k_BackingField,the methods set and get names have the format set_PropertyName and get_PropertyName where PropertyName is the name of property.

    For example, your Settings class is compiled as follows:

    [Serializable]
    public class Settings : BaseClass
    {
        public Settings(){}
    
        // Properties
        [CompilerGenerated]
        private bool k__BackingField;
    
        [CompilerGenerated]
        private bool k__BackingField;
    
        [CompilerGenerated]
        public void set_Value1(bool value)
        {
            this.k__BackingField = value;
        }
    
        [CompilerGenerated]
        public bool get_Value1()
        {
            return this.k__BackingField;
        } 
    
        [CompilerGenerated]
        public void set_Value2(bool value)
        {
            this.k__BackingField = value;
        }
    
        [CompilerGenerated]
        public bool get_Value2()
        {
            return this.k__BackingField;
        }
    }
    

    If you wish exclude this backing fields you can use this method:

    public IEnumerable GetFields(Type type)
    {
        return type
            .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
            .Where(f => f.GetCustomAttribute() == null);
    }
    

提交回复
热议问题