只有当第一个对象实现了第二个对象所需的接口时,如何在C#中的运行时组合两个对象



假设我有两个类。我想把A班分成B班。

然而,为了使其有效,类B必须实现类a所需的一组特定接口。

我如何将类A与它需要类B实现的接口列表相关联?

我想这样做,以便在运行时,某种类型的控制器可以决定是否将一个对象添加到另一个对象。只有当b实现了a所需的所有接口时,它才会将a添加到b。

我希望这是有道理的!谢谢

就我而言,您或多或少需要以下代码。我在代码中写了很多注释,所以我不会试图详细解释,而是让代码来进行对话

// I defined a couple of interfaces for test purposes
public interface IA { }
public interface IB : IA { }
public interface IC : IB { }
// ObjectB implements IB thereforce IA as well
public class ObjectB : IB { }

public class ObjectA {
/// <summary>
/// Interfaces that Object B must implement
/// </summary>
private readonly HashSet<Type> _interfacesObjectBMustImplement = new HashSet<Type>();
/// <summary>
/// Adds an interface requirement for object B to implement
/// </summary>
/// <param name="requiredInterface">Type of required interface</param>
public void AddrequiredInterface(Type requiredInterface) {
var isInterface = requiredInterface.IsInterface;
if (isInterface == false) {
throw new Exception($"{requiredInterface.Name} is not an interface");
}
var added = _interfacesObjectBMustImplement.Add(requiredInterface);
if (added == false) {
throw new Exception($"{requiredInterface.Name} is aready added");
}
}
/// <summary>
/// Clear the required interface requirements
/// </summary>
public void ClearRequiredInterfaces() {
_interfacesObjectBMustImplement.Clear();
}
/// <summary>
/// Checks whether object A can be composed into <see cref="T" />
/// </summary>
/// <typeparam name="T">Type of target object</typeparam>
/// <param name="targetObjectB">Target object instance</param>
/// <returns></returns>
public bool CanBeComsposedInto<T>(T targetObjectB) {
var allInterfaces = typeof(T).GetInterfaces();
return _interfacesObjectBMustImplement.IsSubsetOf(allInterfaces);
}
}

//Creates an object of type ObjectA
var a = new ObjectA(); 
// Add requirement of IA
a.AddrequiredInterface(typeof(IA));
// Add requirement of IB
a.AddrequiredInterface(typeof(IB));
// This is true because a require IA and IB and ObjectB implements both
var canBeAddedInto = a.CanBeComsposedInto(new ObjectB());

最新更新