2010-12-02 12 views

답변

42

아니, is 만하지 주어진 Type에 대한 객체의 종류를 확인하기 위해 작동합니다. 원하는 대상 : :

if (attr != null && typeof(IInterface).IsAssignableFrom(type)) 

여기에주의하십시오. 나는 거의 typeof(...)으로 전화를 사용합니다. 기본적으로 true를 반환하려면 대상이 "상위"유형이어야하고 인수는 "하위"유형이어야합니다.

2

안녕 type.GetInterfaces() or type.GetInterface()을 사용하면 해당 유형이 구현하는 인터페이스를 가져올 수 있습니다.

0

주어진 최악의 시나리오;

당신이 클래스의 모든 속성 위에 반사를 사용하는 경우 ...

public List<PropertyInfo> FindProperties(Type TargetType) { 

    MemberInfo[] _FoundProperties = TargetType.FindMembers(MemberTypes.Property,   
    BindingFlags.Instance | BindingFlags.Public, new 
    MemberFilter(MemberFilterReturnTrue), TargetType); 

    List<PropertyInfo> _MatchingProperties = new List<PropertyInfo>(); 

    foreach (MemberInfo _FoundMember in _FoundProperties) { 
    _MatchingProperties.Add((PropertyInfo)_FoundMember); } 

    return _MatchingProperties; 

} 

는 IInterface 몇 가지 일반적인 인터페이스

public void doSomthingToAllPropertiesInDerivedClassThatImplementIInterface() { 

     IList<PropertyInfo> _Properties = FindProperties(this.GetType()); 
     foreach (PropertyInfo _Property in _Properties) 
     { 

      if (_Property.PropertyType.GetInterfaces().Contains(typeof(IInterface))) 
      { 
       if ((IInterface)_Property.GetValue(this, null) != null) 
       { 
         ((IInterface)_Property.GetValue(this, null)).SomeIInterfaceMethod(); 
       } 
      } 
     } 
    } 
에게 있습니다
관련 문제