如何测试一个类是否实现了另一个类的所有接口?

时间:2015-06-04 19:26:35

标签: c# interface components

我正在使用C#和Unity。

我将类添加为其他类的组件,其中一些组件相互依赖。我希望找到一种方法来遍历组件的所有接口,并测试它所添加的类是否也实现了这些接口。

一个例子:

public class Entity : MonoBehaviour, IEntity, IUpgrades, ITestInterface1
{
    public T AddEntityComponent<T>() where T : MonoBehaviour, IComponent
    {
        // I would hope to run the test here:
        // Ideally the test would return true 
        // for ComponentA and false for ComponentB
        T thisComponent = gameObject.GetOrAddComponent<T>();
        return thisComponent;
    }
}

public class ComponentA : MonoBehaviour, IComponent, ITestInterface1
{
}

public class ComponentB : MonoBehaviour, IComponent, ITestInterface2
{
}

更新:根据Marc Cals的建议,我添加了一些代码如下:

public T AddEntityComponent<T>() where T : MonoBehaviour, IComponent
{
    Type[] entityTypes = this.GetType().GetInterfaces();
    Type[] componentTypes = typeof(T).GetInterfaces();

    List<Type> entityTypeList = new List<Type>();
    entityTypeList.AddRange(entityTypes);

    foreach (Type interfacetype in componentTypes)
    {
        if (entityTypeList.Contains(interfacetype))
        {
            continue;
        }
        else
        {
            return null;
        }
    }
    T thisComponent = gameObject.GetOrAddComponent<T>();
    return thisComponent;
}

由于我项目的混乱状态,我还不能完全测试它,但看起来它应该做我需要的东西。

1 个答案:

答案 0 :(得分:2)

您可以使用Type.GetInterfaces()获取对象的界面,然后比较两者。

相关问题