c# - 如何检查对象是否派生自接口(interface)?

标签 c# interface polymorphism derived-class

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

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

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

最佳答案

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

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

你可以只写if (obj is IFile)

关于c# - 如何检查对象是否派生自接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12413201/

相关文章:

function - Golang 函数指针作为结构的一部分

java - 为什么答案会是 "GOOD"?

java - 如何在 java 上显示所有对象

c# - 多态,调用父类的子方法

c# - 替换 css 中的大小参数

c# - 如何从 lambda 函数访问 S3 存储桶中的文件

c# - 使用接口(interface) - 设计模式方面

c# - 在 C# 中绘图的代码效率?

c# - 如何创建安装最新 NuGet 依赖项的项目模板

java.lang.StackOverflowError : null when serializing an object using gson