0

我有以下带有索引器的 C# 泛型类:

public class MySpecializedContainer<T> where T : new()
{
    private InternalContainer<Element> container;
    public T this[int index]
    {
        set 
        {
            ConvertTToElement( value, container[index] );
        }
        get
        {
            T obj = new T();
            Element elem = container[index];
            ConvertElementToT( elem, obj );
            return obj;
        }
    }
}

正如你所看到的,我的班级假装 Element 的内部容器是 T 的容器,只要我可以将 Element 转换为 T 就可以工作,反之亦然。

我遇到的问题如下:

以下将按预期工作,因为它将有效地更改内部容器中的实际元素:

public class MyClass {
   public int a ;
}
MySpecializedContainer<MyClass> container = ...;
MyClass temp = container[18];
temp.a = 5;
container[18] = temp;

但这个更简单的版本不会:

container[18].a = 5;

这只会更改 get 访问器在索引器中创建的副本...

有什么办法可以使这项工作?

否则我有一个解决方案,至少可以使这个语句“container[18].a=5”不编译,但我真的很想支持它。

谢谢

4

2 回答 2

1

No, it's not possible (without major changes to the way your existing code works).

In order to get this to work the MyClass instance returned would need to be smart enough to know when it's changed and to update the underlying Element when that happens. This isn't possible with a mutable field. If it was a virtual property then you have a shot.

If we modify MyClass like so:

public class MyClass 
{
   public virtual int a {get;set;}
}

Then we can create a special subclass of it within the container:

public class MySpecializedContainer<T> where T : new()
{
    private class MySubClass : MyClass
    {
        private Element wrappedElement;
        public MySubClass(Element wrappedElement)
        {
            this.wrappedElement = wrappedElement;
        }
        public override int a
        {
            set
            {
                base.a = value;
                wrappedElement.Update(value);
            }
        }
    }
}

You'll need to update the ConvertElementToT accordingly as well so that you create a new instance of MySubClass and pass in the appropriate Element object.

So the lesson here is don't use public fields.

于 2013-01-31T22:40:00.647 回答
1

Element如果和之间存在引用转换,您只能真正做您想做的事情T。然后在您的索引器中,您可以将对转换为的内部对象的引用传回T.

于 2013-01-31T22:31:02.467 回答