There is a base class which has one method of generic type and I am sure that in my derived I will be returning a string. This is my code:
public abstract class Base
{
public virtual T GetSomething<T>()
{
return default(T);
}
}
public class Extended : Base
{
public override string GetSomething<string>()
{
return string.Empty;
//return base.GetSomething<T>();
}
}
But this code doesn't compile. Can anybody spot the 开发者_JS百科mistake? I am sure that in my Extended class I want to return string only. How do I solve this?
You cannot override a generic method with a concrete implementation; that's not how generics work. The Extended
class must be able to handle calls to GetSomething<int>()
for example.
In other words, the signature for an overriding method must be identical to the method it is overriding. By specifying a concrete generic implementation of the method, you change its signature.
Consider using this approach:
public override T GetSomething<T>()
{
if (typeof(T) == typeof(string))
return string.Empty;
return base.GetSomething<T>();
}
Note that the JIT should optimize away the conditional when compiling a particular instantiation of this method. (If it doesn't then it's not a very good JIT!)
(The syntax for your override is technically correct, but fails for other reasons as well. For example, you can't use the keyword string
as a generic parameter name. And if you could, your code still wouldn't do what you want, nor would it compile, since the compiler would be unable to find a method with that signature on a supertype.)
精彩评论