【发布时间】: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