2008-09-16 4 views
3

여기 내가하고있는 일은 다음과 같습니다.System.Type 변수에서 "is"연산자를 사용하는 방법?

object ReturnMatch(System.Type type) 
{ 
    foreach(object obj in myObjects) 
    { 
     if (obj == type) 
     { 
      return obj; 
     } 
    } 
} 

그러나 obj가 type의 하위 클래스이면 일치하지 않습니다. 하지만 나는 is 연산자를 사용하는 것과 같은 방식으로 함수를 반환하고자합니다.

isis

코드를 더 깨끗하게 만드시겠습니까?

답변

4

나는 일지 어떨지 방법을 사용했습니다.

Type theTypeWeWant; // From argument or whatever 
foreach (object o in myCollection) 
{ 
    if (theTypeWeWant.IsAssignableFrom(o.GetType)) 
     return o; 
} 

하거나 문제를 작동하지 않을 수있는 또 다른 방법은 일반적인 방법을 사용하는 것입니다

private T FindObjectOfType<T>() where T: class 
{ 
    foreach(object o in myCollection) 
    { 
     if (o is T) 
      return (T) o; 
    } 
    return null; 
} 

(코드는 메모리에서 작성 및 테스트되지 않음)

2

아마도

type.IsAssignableFrom(obj.GetType()) 
+0

을하면 그럴 수 없어 use operator 'is'이것은 최고의 솔루션이 될 것입니다 ... – Jonas

0

is 연산자는 다른 obeject (보통 수퍼 클래스)로 하나 개의 객체를 캐스팅 '안전'이 될 것입니다 여부를 나타냅니다이다.

if(obj is type) 

OBJ 그 후는 (타입) OBJ로 OBJ 캐스팅 '안전'그대로 if 문이 succeede 것이다 형 '타입'또는 서브 클래스 인 경우.

은 다음을 참조하십시오 http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx

0

당신이 자신을 키워드 "는"사용할 수없는 이유가 있습니까?

foreach(object obj in myObjects) 
{ 
    if (obj is type) 
    { 
    return obj; 
    } 
} 

편집 - 내가 누락 된 부분을 봅니다. Isak의 제안은 올바른 것입니다. 나는 그것을 시험하고 확인했다.

class Level1 
    { 
    } 

    class Level2A : Level1 
    { 
    } 

    class Level2B : Level1 
    { 
    } 

    class Level3A2A : Level2A 
    { 
    } 


    class Program 
    { 
    static void Main(string[] args) 
    { 
     object[] objects = new object[] {"testing", new Level1(), new Level2A(), new Level2B(), new Level3A2A(), new object() }; 


     ReturnMatch(typeof(Level1), objects); 
     Console.ReadLine(); 
    } 


    static void ReturnMatch(Type arbitraryType, object[] objects) 
    { 
     foreach (object obj in objects) 
     { 
     Type objType = obj.GetType(); 

     Console.Write(arbitraryType.ToString() + " is "); 

     if (!arbitraryType.IsAssignableFrom(objType)) 
      Console.Write("not "); 

     Console.WriteLine("assignable from " + objType.ToString()); 

     } 
    } 
    } 
+0

예 : C#은 그것을 허용하지 않습니다 ... –

+0

아하 그럴만 한 나, 당신은 _hard_coding_ 코드 자체에 타입이 아니라 Reflection을위한 Type 변수를 전달합니다. 비교. – icelava

관련 문제