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

本文关键字:另一个 接口 实现 是否 何测试 测试 一个 | 更新日期: 2023-09-27 17:53:33

我使用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;
}

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

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

您可以使用Type.GetInterfaces()来获取对象的接口,然后比较两者