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)
实际上我有来自该接口的数百个派生类,我试图避免检查每种类型,并且当我从该类型创建另一个类时必须添加检查.
is
操作员工作或你可以做:
if (someInstance is IExampleInterface) { ... }
Run Code Online (Sandbox Code Playgroud)要么
if(typeof(IExampleInterface).IsAssignableFrom(type)) {
...
}
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
3071 次 |
最近记录: |