[英]Type parameter declaration must be an identifier not a type
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 mistake?
任何人都可以发现错误吗? I am sure that in my Extended class I want to return string only.
我确信在我的Extended类中我只想返回字符串。 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. 例如,
Extended
类必须能够处理对GetSomething<int>()
调用。
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. 请注意,JIT应该在编译此方法的特定实例时优化掉条件。 (If it doesn't then it's not a very good JIT!)
(如果没有那么它不是一个非常好的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.) (覆盖的语法在技术上是正确的,但也因其他原因而失败。例如,您不能将关键字
string
用作通用参数名称。如果可以,您的代码仍然无法执行您想要的操作也不会编译,因为编译器将无法在超类型上找到具有该签名的方法。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.