我有以下層次結構:
class Animal
class Dog : Animal
class Cat : Animal
我有一個List<Animal>集合,想制作一個方法來回傳所有的貓或所有的狗。但是我不知道如何根據型別變數過濾串列元素。所以像這樣:
int AnimalsOfType(Type animalType)
{
// Gives error "animalType is a variable but is used like a type".
return animals.OfType<animalType>().Count;
}
uj5u.com熱心網友回復:
using System.Linq;
int AnimalsOfType(Type animalType)
{
return animals.Count(a => a.GetType() == animalType);
}
uj5u.com熱心網友回復:
這里最有效的方法是使用MakeGenericMethod和CreateDelegate創建泛型方法的委托。您可以將這些委托快取在字典中
static Dictionary<Type, Func<List<Animal>, int>> _methods = new Dictionary<Type, Func<List<Animal>, int>>();
static int CountOfType<T>(List<Animal> source) =>
source.Count(a => a is T);
int AnimalsOfType(List<Animal> animals, Type animalType)
{
if(!_methods.TryGetValue(animalType, out var dlgt))
{
dlgt = (Func<List<Animal>, int>)
this.GetType().GetMethod("CountOfType")
.MakeGenericMethod(animalType)
.CreateDelegate(typeof(Func<List<Animal>, int>)));
_methods[animalType] = dlgt;
}
return dlgt(animals);
}
第一次呼叫此方法時,每種型別都有一個小的啟動成本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362169.html
上一篇:使用第二個陣列計算陣列中的唯一值
下一篇:盡管提供了函式體,但仍期待它
