从getType()中排除属性.GetProperties()

dan*_*ier 25 .net c# reflection

嗨,我正在使用C#在类库中工作,我有一些带有一些属性的类.

我只想知道我是否可以添加一些内容来从getType().GetProperties()中排除一些属性.

我想要的一个例子:

课堂考试

{

class Test
{
    public string one { get; set; }
    public string two {get ; set;}
}
Run Code Online (Sandbox Code Playgroud)

}

如果我这样做:

static void Main(string [] args)

{

static void Main(string[] args)
{

       Test t = new Test();
       Type ty = t.GetType();
       PropertyInfo[] pinfo = ty.GetProperties();

       foreach (PropertyInfo p in pinfo)
       {
           Console.WriteLine(p.Name);
       }
  }
Run Code Online (Sandbox Code Playgroud)

}

我希望输出是这样的:

或者只是其中一个属性.

有可能做那样的事吗?我不知道C#中是否有某种修饰符或注释,这使我能够按照自己的意愿行事.

谢谢.

bni*_*dyc 31

扩展方法和属性将帮助您:

public class SkipPropertyAttribute : Attribute
{
}

public static class TypeExtensions
{
    public static PropertyInfo[] GetFilteredProperties(this Type type)
    {
        return type.GetProperties().Where(pi => pi.GetCustomAttributes(typeof(SkipPropertyAttribute), true).Length == 0).ToArray();
    }       
}

public class Test
{
    public string One { get; set; }

    [SkipProperty]
    public string Two { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var t = new Test();
        Type ty = t.GetType();

        PropertyInfo[] pinfo = ty.GetFilteredProperties();
        foreach (PropertyInfo p in pinfo)
        {
            Console.WriteLine(p.Name);
        }

        Console.ReadKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

更优雅的实施GetFilteredProperties(感谢Marc Gravell):

public static class TypeExtensions
{
    public static PropertyInfo[] GetFilteredProperties(this Type type)
    {
        return type.GetProperties()
              .Where(pi => !Attribute.IsDefined(pi, typeof(SkipPropertyAttribute)))
              .ToArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有关信息,`Attribute.IsDefined`可能更有效,但一个很好的答案. (3认同)

Jar*_*yer 6

您可以在类型上添加自定义属性.

public class DoNotIncludeAttribute : Attribute
{
}

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

    [DoNotInclude]
    public string Two { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后,在运行时中,您可以搜索未隐藏的属性.

foreach (var property in properties.Where(p => !p.IsMarkedWith<DoNotIncludeAttribute>())
{
    // do something...
}
Run Code Online (Sandbox Code Playgroud)

它不会被隐藏,但它不会出现在枚举中.