2

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

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

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

4

6 回答 6

8

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

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

你可以只写if (obj is IFile)

于 2012-09-13T19:14:22.497 回答
6
  1. is运营商工作,或者你可以这样做:

    if (someInstance is IExampleInterface) { ... }
    
  2. 或者

    if(typeof(IExampleInterface).IsAssignableFrom(type)) {
     ...
    }
    
于 2012-09-13T19:17:17.433 回答
3

您将错误的参数传递给is. 正确的是

if (obj is file) {
    // ...
}

file但是,如果您有一个直接接受参数的方法的重载,那就更好了。事实上,接受 an 的人如何object有效地使用它还不清楚。

于 2012-09-13T19:15:05.873 回答
2

你可以使用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任何继承的类或接口的接口。)

于 2012-09-13T19:14:54.070 回答
2
If( yourObject is InterfaceTest)
{
   return true;
}
于 2012-09-13T19:15:20.510 回答
1

您可以创建如下扩展方法

    /// <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)))
    { }
于 2012-09-13T19:17:24.210 回答