![](/img/trans.png)
[英]Loop through GetType().GetProperties() and bind each property with asp-for (Razor Pages)
[英]Exclude property from getType().GetProperties()
嗨,我正在使用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#中是否有某種修飾符或注釋,這使我能夠按照自己的意願行事。
謝謝。
擴展方法和屬性將幫助您:
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<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...
}
它不會被隱藏,但它不會出現在枚舉中。
我不確定這個域名是什么,所以我出去了...
通常,您要使用Attribute
來標記要包含在元數據搜索中的屬性,而不是相反。
使用PropertyInfo對象,您可以檢查屬性的GetCustomAttributes。 因此,您可以在聲明屬性時向屬性添加屬性,然后在反映屬性時,只能選擇使用所需屬性標記的屬性。
當然,如果你真的想以某種方式阻止某人反思性地獲取你的屬性,這不是你想要的解決方案。
編輯:我很抱歉你想要GetCustomAttributes,修復。 請參閱: http : //msdn.microsoft.com/en-us/library/kff8s254.aspx
我不認為你可以直接這樣做,但你可以添加自己的自定義屬性並自己過濾掉它們......
雖然我更喜歡,並且我將使用屬性方式,但我確實以不同的方式工作,這可能有助於OP。
這是一個例子:
PropertyInfo[] properties = record.GetType().GetProperties().Where(p => !"Description".Equals(p.Name)).ToArray();
這將排除任何名為“Description”的屬性。 如果您無法更改包含屬性的類,則可以選擇此選項。 同樣,我更喜歡上面提到的屬性方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.