【问题标题】:How to check that type is inherited from some interface c#如何检查该类型是从某个接口 C# 继承的
【发布时间】:2011-05-19 02:17:09
【问题描述】:

我有以下内容:

Assembly asm = Assembly.GetAssembly(this.GetType());

foreach (Type type in asm.GetTypes())
{
    MyAttribute attr = Attribute.GetCustomAttribute(type, typeof(MyAttribute))    as MyAttribute;
     if(attr != null && [type is inherited from Iinterface])
     {
        ...
     }

}

如何检查类型是从 MyInterface 继承的?是否 keywork 会以这种方式工作?

谢谢。

【问题讨论】:

    标签: c# reflection inheritance interface


    【解决方案1】:
    【解决方案2】:

    不,is 仅适用于检查 对象 的类型,不适用于给定的 Type。你要Type.IsAssignableFrom:

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

    注意这里的顺序。我发现我几乎总是使用typeof(...) 作为调用的目标。基本上要让它返回 true,目标必须是“父”类型,而参数必须是“子”类型。

    【讨论】:

      【解决方案3】:

      嗨 您可以使用type.GetInterfaces() or type.GetInterface() 来获取该类型实现的接口。

      【讨论】:

        【解决方案4】:

        意识到这已经很晚了,但将其留在这里以供参考: 我发现 is 操作员完成了这项工作 - 来自 MSDN - http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.71).aspx

        在 Jon Skeets 回答中使用 resharper,也给了我“是”作为建议。

        【讨论】:

          【解决方案5】:

          考虑到最坏的情况;

          如果您对类中的所有属性使用反射...

          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();  
                          }
                      }
                  }
              }
          

          【讨论】:

            猜你喜欢
            • 2023-03-22
            • 2019-06-25
            • 1970-01-01
            • 1970-01-01
            • 2021-06-23
            • 1970-01-01
            • 2016-09-02
            • 2014-03-05
            • 1970-01-01
            相关资源
            最近更新 更多