[英]Reflection GetProperties should exclude unwanted children properties on certain datatype
我肯定會遺漏明顯的東西。我正在構建一個內部應用程序,並正在反思我們的一些內部dll並以樹狀視圖顯示它們
Treeview是按需加載的,對於展開后的每個屬性,我都會得到子級(如果有)。 當孩子是datetime,string,decimal等時。然后再次進行擴展,我不應該獲取string或datetime的所有內部屬性,等等。 它不應該返回任何東西。我嘗試了很少的bindingFlags,但是我們沒有成功。
我正在使用以下方法,但還不夠好。
public static PropertyInfo[] GetPropertiesByType(this Type t)
{
if (!t.IsPrimitive
|| t != typeof (System.Decimal)
|| t != typeof (System.String)
|| t != typeof(System.DateTime)
|| t != typeof (System.DateTime?))
{
return t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.OrderBy(p => p.Name).ToArray();
}
return new PropertyInfo[0];
}
我想要的是,在獲取屬性時,應排除所有不相關的內部屬性。
EG客戶有訂單,訂單有OrderedDate。使用樹狀視圖時,單擊客戶,得到訂單,單擊訂單,單擊orderdate時得到OrderDate,我應該沒有屬性。我得到“ HasValue和value”並擴展值並得到所有日期時間的東西。
當屬性是字符串時也是如此,我不應該看到字符和長度。
有什么建議么
您應該手動檢查基本類型並返回一個空數組。 您可以在這里找到wuestion的答案, 以檢查類型是否為原始類型
if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) || ... )
{
// Is Primitive, or Decimal, or String
}
所以基本上你可以做
public static PropertyInfo[] GetPropertiesByType(this Type t)
{
if (t.IsPrimitive || t == typeof(Decimal) || t == typeof(String) || ... )
{
return //empty array
}
return t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.OrderBy(p => p.Name).ToArray();
}
-Update
public static PropertyInfo[] GetPropertiesByType(this Type t)
{
if (!t.IsPrimitive
|| t != typeof (System.Decimal)
|| t != typeof (System.String)
|| t != typeof(System.DateTime)
|| t != typeof (System.DateTime?))
{
return t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.OrderBy(p => p.Name).ToArray();
}
else
return new PropertyInfo[0];
}
擴展之前,應檢查Type.FullName屬性,如果類型不在您的命名空間中,則不要擴展。
為了詳細說明,MSDN的以下代碼說明了FullName的作用:
Type t = typeof(Array);
Console.WriteLine("The full name of the Array type is {0}.", t.FullName);
/* This example produces the following output:
The full name of the Array type is System.Array.
*/
例如,您可以測試FullName是否以“ System”開頭。 或“微軟”。 並且不要擴展這些屬性。
也許:
public static PropertyInfo[] GetPropertiesByType(this Type t)
{
if (!typeof (MyBasePropertyClass).IsAssignableFrom(t))
return new PropertyInfo[0];
return t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.OrderBy(p => p.Name)
.ToArray();
}
其中MyBasePropertyClass是您的實體的基類。
if (!t.IsPrimitive
|| t != typeof (System.Decimal)
|| t != typeof (System.String)
|| t != typeof(System.DateTime)
|| t != typeof (System.DateTime?))
應該
if (!t.IsPrimitive
&& t != typeof (System.Decimal)
&& t != typeof (System.String)
&& t != typeof(System.DateTime)
&& t != typeof (System.DateTime?))
System.String
由於所有類型不是System.String
或System.Decimal
並且您將它們與OR運算符組合在一起,因此您的條件將始終為true。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.