C #에서 제네릭 메서드의 형식 매개 변수 확인
C #에서 다음과 같이 할 수 있습니까?
public void DoSomething<T>(T t)
{
if (T is MyClass)
{
MyClass mc = (MyClass)t
...
}
else if (T is List<MyClass>)
{
List<MyClass> lmc = (List<MyClass>)t
...
}
}
예:
if (typeof(T) == typeof(MyClass))
{
MyClass mc = (MyClass)(object) t;
}
else if (typeof(T) == typeof(List<MyClass>))
{
List<MyClass> lmc = (List<MyClass>)(object) t;
}
객체로의 캐스트를 통해 이동해야하는 것은 약간 이상하지만 제네릭이 작동하는 방식 일뿐입니다. 제네릭 유형에서 예상하는 것만 큼 많은 변환이 발생하지 않습니다.
물론 또 다른 대안은 일반적인 실행 시간 검사를 사용하는 것입니다.
MyClass mc = t as MyClass;
if (mc != null)
{
// ...
}
else
{
List<MyClass> lmc = t as List<MyClass>;
if (lmc != null)
{
// ...
}
}
t
물론 null이면 첫 번째 코드 블록과 다르게 동작합니다 .
나는 가능하면 이런 종류의 코드를 피 하려고 노력할 것입니다. 가끔 필요할 수도 있지만, 제네릭 메서드의 아이디어는 모든 유형에 대해 동일한 방식으로 작동하는 제네릭 코드 를 작성할 수 있다는 것입니다.
2017 년이고 이제 패턴 일치가있는 C # 7이 있습니다. 유형 T가 상속되는 경우 다음 object
과 같이 코딩 할 수 있습니다.
void Main()
{
DoSomething(new MyClass { a = 5 });
DoSomething(new List<MyClass> { new MyClass { a = 5 }, new MyClass { a = 5 }});
}
public void DoSomething(object t)
{
switch (t)
{
case MyClass c:
Console.WriteLine($"class.a = {c.a}");
break;
case List<MyClass> l:
Console.WriteLine($"list.count = {l.Count}");
break;
}
}
class MyClass
{
public int a { get; set;}
}
Starting with C# 7, you can do this in a concise way with the is
operator:
public void DoSomething<T>(T value)
{
if (value is MyClass mc)
{
...
}
else if (value is List<MyClass> lmc)
{
...
}
}
See documentation: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is#pattern-matching-with-is
I believe there's something wrong in your design. You want to compare between types in an already generic method. Generics are meant to deal with type-variable situation. I recommend to do it this way..
//Generic Overload 1
public void DoSomething<T>(T t)
where T : MyClass
{
...
}
//Generic Overload 2
public void DoSomething<T>(T t)
where T : List<MyClass>
{
...
}
ReferenceURL : https://stackoverflow.com/questions/2004508/checking-type-parameter-of-a-generic-method-in-c-sharp
'UFO ET IT' 카테고리의 다른 글
Checkstyle에서 파일에 대한 모든 검사를 억제하는 방법은 무엇입니까? (0) | 2021.01.13 |
---|---|
Delphi : StringList Delimiter는 Delimiter가 설정되어 있어도 항상 공백 문자입니다. (0) | 2021.01.12 |
다른 요소의 높이와 일치하도록 버튼의 높이를 얻는 방법은 무엇입니까? (0) | 2021.01.12 |
행이 문자열과 일치하는 데이터 프레임에서 행 제거 (0) | 2021.01.12 |
Java에는 C ++와 같은 이니셜 라이저 목록이없는 이유는 무엇입니까? (0) | 2021.01.12 |