What is it called when trying to overload a function based purely on the return type?
ie:
Public String DoWork()
Public int DoWork()
You cannot do the above, right?
Is that called covar开发者_运维技巧iance?
It's still called a "method overload" but sometimes you'll hear the more verbose "return-type method overload." It is not possible in C#.
From the C# specification:
The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.
No, covariance refers to changing the return type when overriding not overloading.
From wikipedia
class A {
}
class B extends A {
}
// Classes demonstrating method overriding:
class C {
A getFoo() {
return new A();
}
}
class D extends C {
B getFoo() {
return new B();
}
}
The alternative is to use generics:
public T DoWork<T>()
{
}
Edited to fix grammar; the return type doesn't get enclosed in angle brackets.
Return type is not included in method's signature. That is why you cannot have two methods that differ only by return type.
You need to use an intermediate type to get this behaviour. Here's a way to do it in C++. I don't know so much C# but I believe it should support this technique.
精彩评论