Programing

유형이 하위 유형인지 또는 객체 유형인지 어떻게 확인합니까?

lottogame 2020. 3. 10. 08:21
반응형

유형이 하위 유형인지 또는 객체 유형인지 어떻게 확인합니까?


C #에서 형식이 다른 형식의 하위 클래스인지 확인하려면 쉽습니다.

typeof (SubClass).IsSubclassOf(typeof (BaseClass)); // returns true

그러나 이것은 실패합니다.

typeof (BaseClass).IsSubclassOf(typeof (BaseClass)); // returns false

OR연산자 를 사용하지 않거나 확장 메서드를 사용 하지 않고 형식이 기본 클래스 자체의 하위 클래스인지 아니면 하위 클래스인지 확인할 수있는 방법이 있습니까?


분명히 요

옵션은 다음과 같습니다.

Type.IsSubclassOf

이미 알고 있듯이 두 유형이 동일하면 작동하지 않습니다. 다음은 샘플 LINQPad 프로그램입니다.

void Main()
{
    typeof(Derived).IsSubclassOf(typeof(Base)).Dump();
    typeof(Base).IsSubclassOf(typeof(Base)).Dump();
}

public class Base { }
public class Derived : Base { }

산출:

True
False

이는 Derived의 서브 클래스 Base이지만 Base(자명하게) 자체의 서브 클래스가 아님을 나타냅니다 .

Type.IsAssignableFrom

자, 이것은 당신의 특정한 질문에 대답 할 것이지만, 또한 당신에게 잘못된 긍정을 줄 것입니다. Eric Lippert가 의견에서 지적했듯이이 방법은 실제로 True위의 두 가지 질문에 대한 답을 반환 True하지만, 원치 않을 수도 있습니다.

void Main()
{
    typeof(Base).IsAssignableFrom(typeof(Derived)).Dump();
    typeof(Base).IsAssignableFrom(typeof(Base)).Dump();
    typeof(int[]).IsAssignableFrom(typeof(uint[])).Dump();
}

public class Base { }
public class Derived : Base { }

다음과 같은 결과가 나타납니다.

True
True
True

마지막으로 True메소드 가 요청한 질문 에만 응답 한 경우 uint[]상속 된 int[]유형이거나 동일한 유형임을 나타내므로 분명히 그렇지 않습니다.

따라서 IsAssignableFrom완전히 정확하지도 않습니다.

isas

귀하의 질문 is과 관련 as하여 "문제" 는 객체에서 작업하고 유형 중 하나를 코드로 직접 작성해야하지만 객체에서는 작동하지 않아야한다는 것입니다 Type.

다시 말해, 이것은 컴파일되지 않습니다 :

SubClass is BaseClass
^--+---^
   |
   +-- need object reference here

이것도 아닙니다 :

typeof(SubClass) is typeof(BaseClass)
                    ^-------+-------^
                            |
                            +-- need type name here, not Type object

이것도 아닙니다 :

typeof(SubClass) is BaseClass
^------+-------^
       |
       +-- this returns a Type object, And "System.Type" does not
           inherit from BaseClass

결론

위의 방법이 귀하의 요구에 맞을 수도 있지만, 질문에 대한 유일한 정답은 추가 확인이 필요하다는 것입니다.

typeof(Derived).IsSubclassOf(typeof(Base)) || typeof(Derived) == typeof(Base);

물론 방법에서 더 의미가 있습니다.

public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
    return potentialDescendant.IsSubclassOf(potentialBase)
           || potentialDescendant == potentialBase;
}

typeof(BaseClass).IsAssignableFrom(unknownType);

대신 Type.IsAssignableFrom을 사용해보십시오 .


Xamarin Forms PCL 프로젝트에서 수행하려는 경우 위의 솔루션을 사용 IsAssignableFrom하면 오류가 발생합니다.

오류 : 'Type'에 'IsAssignableFrom'에 대한 정의가 포함되어 있지 않으며 'Type'유형의 첫 번째 인수를 허용하는 확장 메소드 'IsAssignableFrom'을 찾을 수 없습니다 (사용 지시문 또는 어셈블리 참조가 누락 되었습니까?)

물체를 IsAssignableFrom요구하기 때문 TypeInfo입니다. 다음 GetTypeInfo()방법을 사용할 수 있습니다 System.Reflection.

typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())


나는 누군가가 나에게 공유하고 그것이 왜 나쁜 생각인지 공유하기를 희망 하여이 답변을 게시하고 있습니다. 내 응용 프로그램에서 Type 속성이 typeof (A) 또는 typeof (B)인지 확인하고 싶습니다. 여기서 B는 A에서 파생 된 클래스입니다. 따라서 내 코드 :

public class A
{
}

public class B : A
{
}

public class MyClass
{
    private Type _helperType;
    public Type HelperType
    {
        get { return _helperType; }
        set 
        {
            var testInstance = (A)Activator.CreateInstance(value);
            if (testInstance==null)
                throw new InvalidCastException("HelperType must be derived from A");
            _helperType = value;
        }
    }
}

나는 여기에 약간 순진한 것처럼 느껴지므로 피드백을 환영합니다.

참고 URL : https://stackoverflow.com/questions/2742276/how-do-i-check-if-a-type-is-a-subtype-or-the-type-of-an-object

반응형