[英]Pass Interface Type As Parameter
我已經知道您可以將接口作為參數傳遞給方法。 這允許您僅指定方法所需的對象的相關成員。 我想要做的是能夠將接口類型作為參數傳遞。
假設我聲明了幾個接口,它們在一系列對象中不均勻地實現,這些對象都形成一個列表/集合。 我可以編寫一個輔助方法,它既可以從列表中獲取對象,也可以將接口類型作為參數,並檢查對象是否實現了接口? 以下代碼顯然是垃圾,但它說明了我想要做的事情:
private bool CheckType(object o, interface intrfce)
{
try
{
object x = (object)(intrfce)o;
return true;
}
catch (InvalidCastException e)
{
return false
}
}
目前我只是計划為接口設置枚舉,並要求所有類公開它們實現的接口的數組/列表。 然后我可以檢查枚舉列表以查看它們具有哪些相關的接口(我只對我創建的接口感興趣 - 我不是在返回IEnumerable
或ICloneable
等之后)或者我可以為每個接口編寫輔助方法接口。 我只是想知道是否有一種更優雅的方式呢?
你可以使用泛型來做到這一點:
private bool CheckType<T>(object o) {
return o is T;
}
你這樣稱呼它:
foreach (object o in myList) {
if (CheckType<MyInterface>(o)) {
... // Do something
}
}
考慮到它是多么容易,你可以在條件本身中做到這一點。
最后,如果您希望僅處理在混合列表中實現特定接口的對象,則可以使用LINQ的OfType
方法來執行此操作,如下所示:
foreach (MyInterface o in myList.OfType<MyInterface>()) {
...
}
你可以這樣做:
private bool CheckType(object o, params Type[] types)
{
//you can optionally check, that types are interfaces
//and throw exceptions if non-interface type was passed
if(types.Any(type => !type.IsInterface))
throw new Exception("Expected types to have only interface definitions");
return types.All(type => type.IsAssignableFrom(o.GetType()));
}
CheckType(new List<int>(), typeof(IEnumerable), typeof(IList)); //returns true
CheckType(0, typeof(IEnumerable)); //return false
要檢查一系列對象,您可以使用以下內容:
private bool CheckAllType(IEnumerable<object> items, params Type[] types)
{
return items.All(item => CheckType(item, types));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.