大家好,我在一个使用C#的类库中工作,我有一些带有一些属性的类。
我只想知道我是否可以添加一些东西来从getType().GetProperties()中排除一些属性。
下面是我想要的示例:
class Test
{
public string one { get; set; }
public string two {get ; set;}
}如果我这样做:
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);
}
}我希望输出是这样的:
one或者仅仅是其中一个属性。
有可能做这样的事情吗?我不知道C#中是否有某种修饰符或注释,它们允许我做我想做的事情。
谢谢。
发布于 2010-01-13 04:18:16
扩展方法和属性将帮助您:
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();
}
}更新:
更优雅的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();
}
}发布于 2010-01-13 03:54:17
您可以在您的类型上添加一个自定义属性。
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; }
}然后,在运行时中,您可以搜索未隐藏的属性。
foreach (var property in properties.Where(p => !p.IsMarkedWith<DoNotIncludeAttribute>())
{
// do something...
}它不会被真正隐藏,但它不会显示在枚举中。
发布于 2010-01-13 03:54:18
我不确定这里的域是什么,所以我要冒险一试...
通常,您要做的是使用Attribute来标记要包括在元数据搜索中的属性,而不是反过来。
https://stackoverflow.com/questions/2051834
复制相似问题