I assume the question is about
return type covariance
It allows a method to return a more-derived type than the one declared in a base type e.g.
public interface ISomeInterface
{
object GetValue();
}
public class SomeClass : ISomeInterface
{
public string GetValue() { return "Hello world"; }
}
This is supported in Java but not in C#. The above will not compile since the return type of SomeClass.GetValue
is string
not object
.
Note that you cannot overload methods based on return-type alone i.e. the following is not valid:
public class SomeClass
{
public int GetValue() { return 1; }
public string GetValue() { return "abc"; }
}
You could do something similar using interfaces although you would need to implement them explicitly to disambiguate:
public interface IValue<T> { T GetValue(); }
public class SomeClass : IValue<int>, IValue<string>
{
string IValue<string>.GetValue() { return "abc"; }
int IValue<int>.GetValue() { return 1; }
}
If the names are the same but the parameters are different then this is method overloading. This is a form of polymorphism (ad-hoc polymorphism). Overloads are resolved statically at compile-type (unless you're using dynamic
in which case they are deferred to run-time).
You can overload on both the number of parameters and their type, so the following are all valid:
public void DoSomething(int value) { }
public void DoSomething(string value) { }
public void DoSomething(int value, string value) { }
Note that you can vary the return type of these methods - methods cannot only be overloaded based on their return type alone but they can differ if their parameter lists are different.
Again this is return type covariance and is not supported in C#.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…