Type parameter declaration must be an identifier not a type

后端 未结 1 542
闹比i
闹比i 2021-01-02 11:13

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 cl         


        
相关标签:
1条回答
  • 2021-01-02 11:20

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

    0 讨论(0)
提交回复
热议问题