如何检查对象是否来自接口?

Tiz*_*izz 2 c# polymorphism interface derived-class

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

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");
}
Run Code Online (Sandbox Code Playgroud)

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

SLa*_*aks 8

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

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

你可以写if (obj is IFile).


Bri*_*ang 5

  1. is 操作员工作或你可以做:

    if (someInstance is IExampleInterface) { ... }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 要么

    if(typeof(IExampleInterface).IsAssignableFrom(type)) {
     ...
    }
    
    Run Code Online (Sandbox Code Playgroud)