Exclude property from getType().GetProperties()

后端 未结 6 1532
故里飘歌
故里飘歌 2020-12-24 07:06

Hi i\'m working in a class library using C#, and i have some classes with some properties.

I just wanna know if i can add something to exclude some properties form t

6条回答
  •  别那么骄傲
    2020-12-24 07:20

    You could put a custom attribute on your type.

    public class DoNotIncludeAttribute : Attribute
    {
    }
    
    public static class ExtensionsOfPropertyInfo
    {
        public static IEnumerable GetAttributes(this PropertyInfo propertyInfo) where T : Attribute
        {
            return propertyInfo.GetCustomAttributes(typeof(T), true).Cast();
        }
        public static bool IsMarkedWith(this PropertyInfo propertyInfo) where T : Attribute
        {
            return property.GetAttributes().Any();
        }
    }
    public class Test
    {
        public string One { get; set; }
    
        [DoNotInclude]
        public string Two { get; set; }
    }
    

    Then, in your runtime, you can search for properties that are not hidden.

    foreach (var property in properties.Where(p => !p.IsMarkedWith())
    {
        // do something...
    }
    

    It won't be really hidden, but it wouldn't show up in the enumeration.

提交回复
热议问题