类型参数声明必须是标识符而非类型 [英] Type parameter declaration must be an identifier not a type

查看:349
本文介绍了类型参数声明必须是标识符而非类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个基类有一个泛型类型的方法,我相信在我的派生中,我将返回一个字符串。这是我的代码:

  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

换句话说,重写方法的签名必须与它重写的方法相同。通过指定该方法的具体通用实现,您可以更改其签名。



考虑使用此方法:

<$ p ()返回string.Empty; $ p $; $ p $ public override T GetSomething< T>()
{
if(typeof(T)== typeof(string))
return string.Empty;

return base.GetSomething< T>();

$ / code>

请注意,JIT应该在编译此特定实例时优化条件方法。 (如果它没有,那么它不是一个很好的JIT!)

(你的覆盖的语法在技术上是正确的,但是由于其他原因也失败了。 ,你不能使用关键字 string 作为通用参数名,如果可以的话,你的代码仍然不会做你想要的,也不会编译它,因为编译器将无法在超类型上找到具有该签名的方法。)


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. 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.)

这篇关于类型参数声明必须是标识符而非类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆