C# generic with constant

前端 未结 5 1248
借酒劲吻你
借酒劲吻你 2020-12-16 11:36

Is there something similar to this C++ template?

template 
class B
{
    int f()
    {
        return A;
    }
}

I want to mak

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 12:05

    A workaround to this limitation is to define a class which itself exposes the literal value you are interested in. For example:

    public interface ILiteralInteger
    {
       int Literal { get; }
    }
    
    public class LiteralInt10 : ILiteralInteger
    {
       public int Literal { get { return 10; } }
    }
    
    public class MyTemplateClass< L > where L: ILiteralInteger, new( )
    {
       private static ILiteralInteger MaxRows = new L( );
    
       public void SomeFunc( )
       {
          // use the literal value as required
          if( MaxRows.Literal ) ...
       }
    }
    

    Usage:

    var myObject = new MyTemplateClass< LiteralInt10 >( );
    

提交回复
热议问题