Case / Switch 및 GetType을 사용하여 객체 결정
가능한 중복 :
C #- '전환 유형'에 대한 더 좋은 대안이 있습니까?
switch
어떤 유형의 객체 를 원한다면 가장 좋은 방법은 무엇입니까?
코드 스 니펫
private int GetNodeType(NodeDTO node)
{
switch (node.GetType())
{
case typeof(CasusNodeDTO):
return 1;
case typeof(BucketNodeDTO):
return 3;
case typeof(BranchNodeDTO):
return 0;
case typeof(LeafNodeDTO):
return 2;
default:
return -1;
}
}
나는 이것이 그렇게 작동하지 않는다는 것을 알고 있지만 어떻게 해결할 수 있는지 궁금합니다. 이 경우 if/else
진술이 적절합니까?
아니면 스위치를 사용 .ToString()
하여 유형에 추가 합니까?
내가하면 정말 로했다 switch
객체의 유형에, 내가 사용하십시오 .ToString()
. 그러나 나는 모든 비용으로 그것을 피할 것입니다 : IDictionary<Type, int>
훨씬 더 잘 할 것입니다. 방문자 는 지나칠 수 있지만 그렇지 않으면 여전히 완벽하게 훌륭한 솔루션입니다.
사용자 정의 형식을 전환하려고 할 때 문제를 직접 해결하지는 않지만 기본 제공 형식 만 전환하려는 다른 사람들을 위해 TypeCode 열거 형을 사용할 수 있습니다 .
switch (Type.GetTypeCode(node.GetType()))
{
case TypeCode.Decimal:
// Handle Decimal
break;
case TypeCode.Int32:
// Handle Int32
break;
...
}
MSDN 블로그 게시물의 많은 질문 : 유형 켜기 는 .NET 에서 유형 켜기를 제공하지 않는 이유에 대한 정보입니다 .
평소와 같이-해결 방법이 항상 존재합니다.
이것은 내 것이 아니지만 불행히도 나는 소스를 잃어 버렸습니다. 유형을 전환 할 수는 있지만 개인적으로 꽤 어색하다고 생각합니다 (사전 아이디어가 더 좋습니다).
public class Switch
{
public Switch(Object o)
{
Object = o;
}
public Object Object { get; private set; }
}
/// <summary>
/// Extensions, because otherwise casing fails on Switch==null
/// </summary>
public static class SwitchExtensions
{
public static Switch Case<T>(this Switch s, Action<T> a)
where T : class
{
return Case(s, o => true, a, false);
}
public static Switch Case<T>(this Switch s, Action<T> a,
bool fallThrough) where T : class
{
return Case(s, o => true, a, fallThrough);
}
public static Switch Case<T>(this Switch s,
Func<T, bool> c, Action<T> a) where T : class
{
return Case(s, c, a, false);
}
public static Switch Case<T>(this Switch s,
Func<T, bool> c, Action<T> a, bool fallThrough) where T : class
{
if (s == null)
{
return null;
}
T t = s.Object as T;
if (t != null)
{
if (c(t))
{
a(t);
return fallThrough ? s : null;
}
}
return s;
}
}
용법:
new Switch(foo)
.Case<Fizz>
(action => { doingSomething = FirstMethodCall(); })
.Case<Buzz>
(action => { return false; })
나는 같은 문제에 직면 하여이 게시물을 보았습니다. 이것이 IDictionary 접근법의 의미입니까?
Dictionary<Type, int> typeDict = new Dictionary<Type, int>
{
{typeof(int),0},
{typeof(string),1},
{typeof(MyClass),2}
};
void Foo(object o)
{
switch (typeDict[o.GetType()])
{
case 0:
Print("I'm a number.");
break;
case 1:
Print("I'm a text.");
break;
case 2:
Print("I'm classy.");
break;
default:
break;
}
}
If so, I can't say I'm a fan of reconciling the numbers in the dictionary with the case statements.
This would be ideal but the dictionary reference kills it:
void FantasyFoo(object o)
{
switch (typeDict[o.GetType()])
{
case typeDict[typeof(int)]:
Print("I'm a number.");
break;
case typeDict[typeof(string)]:
Print("I'm a text.");
break;
case typeDict[typeof(MyClass)]:
Print("I'm classy.");
break;
default:
break;
}
}
Is there another implementation I've overlooked?
I'd just use an if statement. In this case:
Type nodeType = node.GetType();
if (nodeType == typeof(CasusNodeDTO))
{
}
else ...
The other way to do this is:
if (node is CasusNodeDTO)
{
}
else ...
The first example is true for exact types only, where the latter checks for inheritance too.
You can do this:
if (node is CasusNodeDTO)
{
...
}
else if (node is BucketNodeDTO)
{
...
}
...
While that would be more elegant, it's possibly not as efficient as some of the other answers here.
You can do this:
function void PrintType(Type t) {
var t = true;
new Dictionary<Type, Action>{
{typeof(bool), () => Console.WriteLine("bool")},
{typeof(int), () => Console.WriteLine("int")}
}[t.GetType()]();
}
It's clear and its easy. It a bit slower than caching the dictionary somewhere.. but for lots of code this won't matter anyway..
One approach is to add a pure virtual GetNodeType() method to NodeDTO and override it in the descendants so that each descendant returns actual type.
Depending on what you are doing in the switch statement, the correct answer is polymorphism. Just put a virtual function in the interface/base class and override for each node type.
I actually prefer the approach given as the answer here: Is there a better alternative than this to 'switch on type'?
There is however a good argument about not implementing any type comparison methids in an object oriented language like C#. You could as an alternative extend and add extra required functionality using inheritance.
This point was discussed in the comments of the authors blog here: http://blogs.msdn.com/b/jaredpar/archive/2008/05/16/switching-on-types.aspx#8553535
I found this an extremely interesting point which changed my approach in a similar situation and only hope this helps others.
Kind Regards, Wayne
참고URL : https://stackoverflow.com/questions/708911/using-case-switch-and-gettype-to-determine-the-object
'Programing' 카테고리의 다른 글
콘솔 제작자에서 리더를 사용할 수 없음 (0) | 2020.06.19 |
---|---|
개별 클래스 이름에 'starts with'선택기를 사용 (0) | 2020.06.19 |
HTML-파일 이름을 선택한 후 이미지 표시 (0) | 2020.06.19 |
'where'절의 SQL 스위치 / 케이스 (0) | 2020.06.19 |
프로그램 내에서 Java 앱을 종료하는 방법 (0) | 2020.06.19 |