6

好的,这就是我想做的。

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 代表实现接口的对象的类?

4

2 回答 2

4
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;
    }
}
于 2012-05-19T20:38:38.873 回答
1

也许你已经知道了,但如果只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);   
    }

    ...
}
于 2012-05-19T20:55:31.963 回答