且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类型参数声明必须是标识符而非类型

更新时间:2022-10-17 23:36:38

不能用一个具体的实现覆盖泛型方法;这不是泛型的工作原理。例如, Extended 类必须能够处理对 GetSomething< int>()的调用。 b
$ b

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



考虑使用此方法:

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