Is there a reasonable approach to “default” type parameters in C# Generics?

前端 未结 5 986
日久生厌
日久生厌 2020-11-27 18:59

In C++ templates, one can specify that a certain type parameter is a default. I.e. unless explicitly specified, it will use type T.

Can this be done or approximated

5条回答
  •  無奈伤痛
    2020-11-27 19:20

    One solution is subclassing. Another one I would use instead, is factory methods (combined with var keyword).

    public class MyTemplate
    {
         public MyTemplate(..args..) { ... } // constructor
    }
    
    public static class MyTemplate{
    
         public static MyTemplate Create(..args..)
         {
             return new MyTemplate(... params ...);
         }
    
         public static MyTemplate Create(...args...)
         {
             return new MyTemplate(... params ...);
         }
    }
    
    var val1 = MyTemplate.Create();
    var val2 = MyTemplate.Create();
    

    In the above example val2 is of type MyTemplate and not a type derived from it.

    A type class MyStringTemplate:MyTemplate is not the same type as MyTemplate. This could pose some problems in certain scenarios. For instance you can't cast an instance of MyTemplate to MyStringTemplate.

提交回复
热议问题