Return derived type from base class method

后端 未结 1 479
[愿得一人]
[愿得一人] 2020-12-31 18:57

I have a class hierarchy that looks similar to this:

public class Base
{
    private List attributes = new List();

    public T          


        
相关标签:
1条回答
  • 2020-12-31 19:20

    Why can't the compiler infer type arguments in the first example?

    Type inference uses method arguments to infer type arguments. In the first example there are no method arguments which can be used to infer type argument.

    Why does it work when called using an extension method?

    Extension method is actually a static method and object which you are 'extending' is passed as an argument to extension method call:

    Extensions.WithAttributesEx<T>(d, "one", "two")
    

    As stated above, type inference uses method arguments to find type arguments. Here type argument can be inferred from the type of first method argument, which is Derived.

    Is there any way to make it work as an instance method on the base class without explicitly specifying type argument?

    Make base class generic and parametrize it with derived class (that is called Curiously Recurring Template Pattern):

    public class Base<T>
        where T : Base<T>
    {
        private List<string> attributes = new List<string>();
    
        public T WithAttributes(params string[] attributes)            
        {
            this.attributes.AddRange(attributes);
            return this as T;
        }
    }
    
    public class Derived : Base<Derived>
    {
    }
    

    Usage:

    Derived d = new Derived().WithAttributes("one", "two").WithAttributes("three");
    
    0 讨论(0)
提交回复
热议问题