Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

c# - The return type of the members on an Interface Implementation must match exactly the interface definition?

According to CSharp Language Specification.

An interface defines a contract that can be implemented by classes and structs. An interface does not provide implementations of the members it defines—it merely specifies the members that must be supplied by classes or structs that implement the interface.

So I a have this:

interface ITest
{
    IEnumerable<int> Integers { get; set; }
}

And what I mean is. "I have a contract with a property as a collection of integers that you can enumerate".

Then I want the following interface Implementation:

class Test : ITest
{
    public List<int> Integers { get; set; }
}

And I get the following compiler error:

'Test' does not implement interface member 'ITest.Integers'. 'Test.Integers' cannot implement 'ITest.Integers' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable'.

As long as I can say my Test class implement the ITest contract because the List of int property is in fact an IEnumerable of int.

So way the c# compiler is telling me about the error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

FYI, the feature you want is called "virtual method return type covariance", and as you have discovered, it is not supported by C#. It is a feature of other object-oriented languages, like C++.

Though we get requests for this feature fairly frequently, we have no plans to add it to the language. It is not a terrible feature; if we had it, I'd use it. But we have many reasons not to do it, including that it is not supported by the CLR, it adds new and interesting failure modes to versionable components, Anders does not think it is a very interesting feature, and we have many, many higher priorities and a limited budget.

Incidentally, though people ask us for virtual method return type covariance all the time, no one ever asks for virtual method formal parameter type contravariance, even though logically they are essentially the same feature. That is, I have a virtual method/interface method M that takes a Giraffe, and I would like to override it/implement it with a method M that takes an Animal.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...