Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net ReadOnlyCollection有什么神奇之处吗_.net_Interface_Readonly Collection - Fatal编程技术网

.net ReadOnlyCollection有什么神奇之处吗

.net ReadOnlyCollection有什么神奇之处吗,.net,interface,readonly-collection,.net,Interface,Readonly Collection,有了这个密码 var b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 }); b[2] = 3; var b=newreadonlycollection(new[]{2,4,2,2}); b[2]=3; 我在第二行得到一个编译错误。我预计会出现运行时错误,因为ReadOnlyCollection实现了IList,并且this[T]在IList接口中有一个setter 我曾尝试复制ReadOnlyCollection的功能,但从

有了这个密码

var b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 });
b[2] = 3;
var b=newreadonlycollection(new[]{2,4,2,2});
b[2]=3;
我在第二行得到一个编译错误。我预计会出现运行时错误,因为
ReadOnlyCollection
实现了
IList
,并且
this[T]
IList
接口中有一个setter


我曾尝试复制ReadOnlyCollection的功能,但从
此[T]
中删除setter是一个编译错误。

它显式实现了IList.Items,这使它成为非公共的,您必须强制转换到接口才能实现它,并实现了一个新的this[…]索引器,该索引器被替代使用,它只有一个get访问器

如果将集合强制转换为IList,代码将编译,但在运行时会失败

不幸的是,我不知道如何在C#中实现这一点,因为在C#中编写索引器需要使用
this
关键字,而您不能编写以下内容:

T IList<T>.this[int index] { get; set; }
tilist.this[int index]{get;set;}
通过显式接口实现,因此只有在执行以下操作时,您才能访问它:

IList<int> b = new ReadOnlyCollection<int>(new[] { 2, 4, 2, 2 });
b[2] = 3;

这并没有什么神奇之处,
ReadOnlyCollection
只是为自己的索引器和实现
IList
接口的索引器提供了不同的实现:

public T Item[int index] { get; }

T IList<T>.Item[int index] { get; set; }

好的,但是如何使用显式实现复制ReadOnlyCollection的功能呢。我看不出如何从接口中删除方法或属性。@EsbenP:您不能从接口中删除方法。。。但是,只有当引用的静态类型是接口而不是实现接口的类时,才可以使用它。好的,如果我有两个索引器,其中一个显式地实现了IList,它就可以在IList中工作。这个[int index]{get{return source[index];}集{throw new NotImplementedException();}}public T this[int index]{get{return source[index];}您已经确定了索引器是如何通过最新编辑实现的。这也是我的想法,但当我在自己实现IList的类中尝试这一点时,就不会了compile@EsbenP:要在类中实现它,语法与文档中显示的签名不同。请参见上面的编辑。@Lasse:您可以使用适当的impl校正。问题是,据我所知,你不能显式地实现一半,隐式地实现一半。你不必,如果你能写的话,你只需抛出一个异常就可以编写setter,然后你只需使用getter就可以实现一个public this[…]索引器。
T IList<T>.this[int index]
{
    // Delegate interface implementation to "normal" implementation
    get { return this[index]; }
    set { throw new NotSupportedException("Collection is read-only."); }
}

public T this[int index]
{
    get { return ...; }
}
public T Item[int index] { get; }

T IList<T>.Item[int index] { get; set; }
((IList<int>)b)[2] = 3;
public T this[int index] { get { ... } }

T IList<T>.this[int index] { get { ... } set { ... } }