gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:51:03 26 4
gpt4 key购买 nike

我有一些派生自接口(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com