如何检查对象是否来自接口?

问题描述 投票:2回答:6

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

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

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

c# interface polymorphism derived-class
6个回答
8
投票

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

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

你可以写if (obj is IFile)


5
投票
  1. is运营商工作或你可以做: if (someInstance is IExampleInterface) { ... }
  2. 要么 if(typeof(IExampleInterface).IsAssignableFrom(type)) { ... }

3
投票

你将错误的参数传递给is。正确的是

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

但是如果你有一个直接接受file参数的方法的重载会更好。事实上,目前尚不清楚如何接受object可以有效地使用它。


2
投票
If( yourObject is InterfaceTest)
{
   return true;
}

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和任何继承的类或接口的接口。)


0
投票

您可以创建如下所示的扩展方法

    /// <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)))
    { }
© www.soinside.com 2019 - 2024. All rights reserved.