我有一些从接口派生的类,我希望能够检入代码以查看传入的对象是否是从该接口派生的,但我不确定该方法是否正在调用...
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");
}
实际上我有来自该接口的数百个派生类,我试图避免检查每种类型,并且当我从该类型创建另一个类时必须添加检查。
is
完全正确。
但是,您需要检查实例本身。
obj.GetType()
返回描述对象实际类的System.Type
类的实例。
你可以写if (obj is IFile)
。
is
运营商工作或你可以做:
if (someInstance is IExampleInterface) { ... }
if(typeof(IExampleInterface).IsAssignableFrom(type)) {
...
}
你将错误的参数传递给is
。正确的是
if (obj is file) {
// ...
}
但是如果你有一个直接接受file
参数的方法的重载会更好。事实上,目前尚不清楚如何接受object
可以有效地使用它。
If( yourObject is InterfaceTest)
{
return true;
}
你可以使用BaseType
:
if (type.BaseType is file)
由于file
是一个接口,使用Type.GetInterfaces来检查type
的底层接口:
if (type.GetInterfaces().Any(i => i.Equals(typeof(file))
或者可能更快一点,使用Type.GetInterface:
if (type.GetInterface(typeof(file).FullName) != null)
(这将搜索type
和任何继承的类或接口的接口。)
您可以创建如下所示的扩展方法
/// <summary>
/// Return true if two types or equal, or this type inherits from (or implements) the specified Type.
/// Necessary since Type.IsSubclassOf returns false if they're the same type.
/// </summary>
public static bool IsSameOrSubclassOf(this Type t, Type other)
{
if (t == other)
{
return true;
}
if (other.IsInterface)
{
return t.GetInterface(other.Name) != null;
}
return t.IsSubclassOf(other);
}
and use it like below
Type t = typeof(derivedFileType);
if(t.IsSameOrSubclassOf(typeof(file)))
{ }