Jeff Wright
Jeff Wright

Reputation: 53

How can you test if one class implements all the interfaces of another?

I'm using C# and Unity.

I have classes that I add as components to other classes, and some of these components depend on each other. I was hoping to find a way to iterate through all of the interfaces of the component, and test the class to which it's being added on whether it implements those interfaces as well.

An example:

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
{
}

Update: based on Marc Cals' suggestion, I've added some code as follows:

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

I can't quite test it yet due to the messy state of my project, but it looks like it should do what I need.

Upvotes: 0

Views: 265

Answers (1)

Marc Cals
Marc Cals

Reputation: 2989

You can use Type.GetInterfaces() to get the interfaces of your objects, and then compare the two.

Upvotes: 2

Related Questions