接口中的自引用
本文关键字:自引用 接口 | 更新日期: 2023-09-27 18:34:38
好的,这就是我想做的。
Class Container<T>
{
T contained;
public void ContainObject(T obj)
{
contained = obj;
if(/*Magical Code That Detects If T Implemtns IContainableObject*/)
{
IContainableObect c = (IContainableObject)obj;
c.NotifyContained(self);
}
}
}
interface IContainableObject
{
public void NotifyContained(Container<REPLACE_THIS>);//This line is important, see below after reading code.
}
Class ImplementingType : IContaiableObject
{
public Container<ImplementingType> MyContainer;
public void NotifyContained(Container<ImplmentingType> c)
{
MyContainer = c;
}
}
Class Main
{
public static void Main(args)
{
ImplementingType iObj = new ImplementingType();
Container<ImplementingType> container = new Container();
container.ContainObject(iObj);
//iObj.MyContainer should now be pointing to container.
}
}
基本上,总结上面的例子,我有一个类型的 T 泛型包装器类型。我希望该包装器类型通知它包含的任何内容它正在被包含(带有其自身的副本!如果包含的对象实现了特定的接口(我知道该怎么做(
但它变得棘手!为什么?好吧,因为容器泛型需要有一个类型。
还记得那句重要的台词吗?
如果REPLACE_THIS是 IContainableObject,则接口的所有实现者都必须使用 IContainerObject,而不是其 NotifyContained 方法中的实现类的名称。
出于显而易见的原因,使用ImplementingType作为接口中的容器类型甚至更糟!
所以我的问题是,我该怎么做才能REPLACE_THIS表示实现接口的对象的类?
class Container<T>
{
T contained;
public void ContainObject(T obj)
{
contained = obj;
var containable = obj as IContainableObject<T>;
if(containable != null)
{
containable.NotifyContained(this);
}
}
}
interface IContainableObject<T>
{
void NotifyContained(Container<T> c);
}
class ImplementingType : IContainableObject<ImplementingType>
{
public Container<ImplementingType> MyContainer;
public void NotifyContained(Container<ImplementingType> c)
{
MyContainer = c;
}
}
编辑:添加具有通用约束的版本
interface IContainer<T>
{
void ContainObject(T obj);
}
class Container<T> : IContainer<T> where T : IContainableObject<T>
{
T contained;
public void ContainObject(T obj)
{
contained = obj;
contained.NotifyContained(this);
}
}
interface IContainableObject<T>
{
void NotifyContained(IContainer<T> c);
}
class ImplementingType : IContainableObject<ImplementingType>
{
public IContainer<ImplementingType> MyContainer;
public void NotifyContained(IContainer<ImplementingType> c)
{
Debug.WriteLine("notify contained");
MyContainer = c;
}
}
也许你已经知道了,但如果只允许IContainableObjects
作为T
你可以像这样声明你的类
class Container<T>
where T : IContainableObject
{
public void ContainObject(T obj)
{
// Here you know that obj does always implement IContainableObject.
obj.NotifyContained(this);
}
...
}