您如何测试一个 class 是否实现了另一个的所有接口?
How can you test if one class implements all the interfaces of another?
我正在使用 C# 和 Unity。
我有 class 作为组件添加到其他 class 的组件,其中一些组件相互依赖。我希望找到一种方法来遍历组件的所有接口,并测试添加它的 class 是否也实现了这些接口。
一个例子:
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()获取对象的接口,然后比较两者。
我正在使用 C# 和 Unity。
我有 class 作为组件添加到其他 class 的组件,其中一些组件相互依赖。我希望找到一种方法来遍历组件的所有接口,并测试添加它的 class 是否也实现了这些接口。
一个例子:
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()获取对象的接口,然后比较两者。