类型参数声明必须是标识符而非类型 [英] Type parameter declaration must be an identifier not a type
问题描述
有一个基类有一个泛型类型的方法,我相信在我的派生中,我将返回一个字符串。这是我的代码:
public abstract class Base
{
public virtual T GetSomething< T>( )
{
return default(T);
$ b public class Extended:Base
{
public override string GetSomething< string>()
{
返回string.Empty;
// return base.GetSomething< T>();
}
}
但是这段代码不能编译。任何人都可以发现错误?我确信在扩展类中,我只想返回字符串。如何解决这个问题?
不能用一个具体的实现覆盖泛型方法;这不是泛型的工作原理。例如, Extended
类必须能够处理对 GetSomething< int>()
的调用。 b
$ b
换句话说,重写方法的签名必须与它重写的方法相同。通过指定该方法的具体通用实现,您可以更改其签名。
考虑使用此方法: 请注意,JIT应该在编译此特定实例时优化条件方法。 (如果它没有,那么它不是一个很好的JIT!) (你的覆盖的语法在技术上是正确的,但是由于其他原因也失败了。 ,你不能使用关键字 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: 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. How do I solve this? You cannot override a generic method with a concrete implementation; that's not how generics work. The 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: 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 这篇关于类型参数声明必须是标识符而非类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<$ p ()返回string.Empty; $ p $; $ p $ public override T GetSomething< T>()
{
if(typeof(T)== typeof(string))
return string.Empty;
return base.GetSomething< T>();
$ / code>
string
作为通用参数名,如果可以的话,你的代码仍然不会做你想要的,也不会编译它,因为编译器将无法在超类型上找到具有该签名的方法。)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>();
}
}
Extended
class must be able to handle calls to GetSomething<int>()
for example.public override T GetSomething<T>()
{
if (typeof(T) == typeof(string))
return string.Empty;
return base.GetSomething<T>();
}
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.)