0

i have noticed a very strange behavior in one of the classes in the TFS API that look like breaking the definition of the language.

I tried to imitate it but without success, I have tried to implement collection but not letting whom who use the class to call the indexer setter, as it been done in WorkitemCollection Class. it's important that error will be presented at completion and not at run time,so exception is't valid. WorkitemCollection is implementing an IReadOnlyList which is implementing a Collection. by definition Collection has Index Public Get And Set. yet this code is returning a compile error:

WorkitemCollection wic=GetWorkitemCollection();
wic[0]=null;

why is this happening? thanks in advance.

4

2 回答 2

2

您可以显式实现一个接口:

int IReadOnlyList.Index
{
    get;
    set;
}

这样你就不能Index在没有先转换对象的情况下调用:

((IReadOnlyList)myObj).Index

请参阅C# 接口。隐式实现与显式实现

于 2013-09-17T10:20:13.120 回答
2

解决方案是显式接口实现。当您使用实现接口的类时,这实质上使该方法成为私有方法。但是,仍然可以通过将类的实例强制转换为实现接口来调用它,因此您仍然需要抛出异常。

public class Implementation : IInterface
{
    void IInterface.SomeMethod()
    {
        throw new NotSupportedException();
    }
}

var instance = new Implementation();
instance.SomeMethod(); // Doesn't compile

var interfaceInstance = (IInterface)instance;
interfaceInstance.SomeMethod(); // Compiles and results in the
                                // NotSupportedException being thrown
于 2013-09-17T10:21:18.683 回答