我有三個類似的串列 List<EmpRoles> , List<EmpVisibility> , List<EmpProps>.
現在我想對它們執行某些操作。首先,我必須檢查該屬性是否屬于串列型別。我有使用 if 阻止類似下面的內容
if ( propertyName == "EmpRoles" || propertyName == "EmpVis" || propertyName == "EmpProps")
有沒有更好的方法來做這件事,或者是否可以放置一些 typeof(list<>) 條件。我知道 typeof(list<>) 在這里不起作用。要么我必須使用 typeof(list) ... 有人可以幫助制作一種通用的方法來識別串列型別屬性嗎?
uj5u.com熱心網友回復:
檢查型別是否為 aList<T>需要確保:
- 通過檢查其
IsGenericType屬性,該型別是通用的, - 通用型基極是
System.List<>通過檢查的結果GetGenericTypeDefinition()對typeof(List<>) T通過檢查型別是您想要的型別GetGenericArguments()
如果所有三個條件都滿足,你就有了你的型別:
var pt = myProperty.PropertyType;
if (pt.IsGenericType &&
pt.GetGenericTypeDefinition() == typeof(List<>)) {
var elementType = pt.GetGenericArguments()[0];
if (elementType == typeof(EmpRoles)) {
...
} else if (elenentType == typeof(EmpVisibility)) {
...
} else if ...
}
uj5u.com熱心網友回復:
您可以從串列中獲取通用引數如下
var list = new List<EmpRoles>
var argType = list.GetType().GenericTypeArguments[0];
在這里argType你會得到typeof(EmpRoles)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/396648.html
