【问题标题】:How to check if an object is derived from an interface?如何检查对象是否从接口派生?
【发布时间】:2012-09-06 22:48:53
【问题描述】:

我有一些从接口派生的类,我希望能够检查代码以查看传入的对象是否从该接口派生,但我不确定方法调用的确切.. .

interface IFile
{
}

class CreateFile : IFile
{
    string filename;
}

class DeleteFile : IFile
{
    string filename;
}

// Input here can be a string or a file
void OperateOnFileString( object obj )
{
    Type theType = obj.GetType();

    // Trying to avoid this ...
    // if(theType is CreateFile || theType is DeleteFile)

    // I dont know exactly what to check for here
    if( theType is IFile ) // its not, its 'CreateFile', or 'DeleteFile'
        print("Its an IFile interface");
    else
        print("Error: Its NOT a IFile interface");
}

实际上,我有数百个来自该接口的派生类,我试图避免必须检查每种类型,并且在我从该类型创建另一个类时必须添加检查。

【问题讨论】:

  • .Net 类型名称应为 UpperCamelCase,接口应以I 开头。
  • 您的编码约定很糟糕,确实降低了代码的可读性。如果您希望其他人阅读您的代码并回答相关问题,我建议您付出更多努力。

标签: c# interface polymorphism derived-class


【解决方案1】:

is 完全正确。
但是,您需要检查实例本身。

obj.GetType() 返回描述对象实际类的System.Type 类的实例。

你可以写if (obj is IFile)

【讨论】:

  • Tizz,SLaks 在这里是正确的。我还建议不要将 'obj' 作为对象传入。如果你传入一个“文件”,任何调用都将被强制传入一个实现“文件”的对象。此外,请注意您的命名约定和大小写。在 C# 中,我们更喜欢使用以 I 开头的接口,因此在这种情况下为 IFile。
【解决方案2】:
  1. is 运营商工作或者你可以这样做:

    if (someInstance is IExampleInterface) { ... }
    
  2. if(typeof(IExampleInterface).IsAssignableFrom(type)) {
     ...
    }
    

【讨论】:

    【解决方案3】:

    您将错误的参数传递给is。正确的是

    if (obj is file) {
        // ...
    }
    

    但是,如果您有一个直接接受file 参数的方法的重载,那就更好了。事实上,接受object 的人如何有效地使用它还不清楚。

    【讨论】:

      【解决方案4】:
      If( yourObject is InterfaceTest)
      {
         return true;
      }
      

      【讨论】:

        【解决方案5】:

        你可以使用BaseType:

        if (type.BaseType is file) 
        

        由于file是一个接口,所以使用Type.GetInterfaces查看type的底层接口:

        if (type.GetInterfaces().Any(i => i.Equals(typeof(file))
        

        或者可能更快一点,使用Type.GetInterface

        if (type.GetInterface(typeof(file).FullName) != null)
        

        (这会搜索type 的接口以及任何继承的类或接口。)

        【讨论】:

          【解决方案6】:

          你可以像下面这样创建一个扩展方法

              /// <summary>
              /// Return true if two types or equal, or this type inherits from (or implements) the specified Type.
              /// Necessary since Type.IsSubclassOf returns false if they're the same type.
              /// </summary>
              public static bool IsSameOrSubclassOf(this Type t, Type other)
              {
                  if (t == other)
                  {
                      return true;
                  }
                  if (other.IsInterface)
                  {
                      return t.GetInterface(other.Name) != null;
                  }
                  return t.IsSubclassOf(other);
              }
          
              and use it like below
          
              Type t = typeof(derivedFileType);
              if(t.IsSameOrSubclassOf(typeof(file)))
              { }
          

          【讨论】:

          • 我不知道你为什么要这样做
          猜你喜欢
          • 2012-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-23
          • 2012-12-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多