从getType()中排除属性.GetProperties()
嗨我正在使用C#在类库中工作,我有一些带有一些属性的类。
我只想知道我是否可以添加一些内容来从getType()中排除一些属性.GetProperties()。
我想要的一个例子:
课堂考试
{
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); }
}
我希望输出是这样的:
一
或只是其中一个属性。
有可能做那样的事吗? 我不知道C#中是否有某种修饰符或注释,这使我能够按照自己的意愿行事。
谢谢。
扩展方法和属性将帮助您:
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(); } }
您可以在类型上添加自定义属性。
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; } }
然后,在运行时中,您可以搜索未隐藏的属性。
foreach (var property in properties.Where(p => !p.IsMarkedWith()) { // do something... }
它不会被隐藏,但它不会出现在枚举中。
我不确定这个域名是什么,所以我出去了…
通常,您要使用Attribute
来标记要包含在元数据搜索中的属性,而不是相反。
使用PropertyInfo对象,您可以检查属性的GetCustomAttributes。 因此,您可以在声明属性时向属性添加属性,然后在反映属性时,只能选择使用所需属性标记的属性。
当然,如果你真的想以某种方式阻止某人反思性地获取你的属性,这不是你想要的解决方案。
编辑:很抱歉你想要GetCustomAttributes,修复。 请参阅: http : //msdn.microsoft.com/en-us/library/kff8s254.aspx
我不认为你可以直接这样做,但你可以添加自己的自定义属性并自己过滤掉它们……