는 방법을 필터에서 항목을 기반으로 컬렉션에서 유형에 저장된 변수

0

질문

나는 다음과 같은 계층:

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;
}
c# casting inheritance list
2021-11-21 02:30:01
2

최고의 응답

0
using System.Linq;

int AnimalsOfType(Type animalType)
{
    return animals.Count(a => a.GetType() == animalType);
}
2021-11-21 05:33:50

감사합니다,하지만 왜 수 없는 변수는 구약의 유형 Type 사용될 형식으로?
K-RUSHer

전달할 수 없는 변수의 유형 System.Type 으로 일반적인 매개 변수는 일반적인 기능이 직접 있습니다. 그 이유는 일반적인 매개 변수로 대체 코드를 컴파일할 때 읽고 이에 응답하는 더 설명
Ibram Reda

할 수 있는 더 단순화 animals.Count(a => a.GetType() == animalType);
Sarin

@시린 네 당신이 맞아요,편집
Ibram Reda
0

가장 효율적인 방법이 여기를 사용하는 것입 MakeGenericMethodCreateDelegate 대리자를 만들 수를 일반적인 방법입니다. 캐시할 수 있습니다 이러한 대리인에서 사전

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);
}

거기에 하나의 작은 시작 비용 첫 번째 시간을 당신은 이 메소드를 호출,당 형식입니다.

2021-11-21 03:01:30

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................