extension method on type and nullable

后端 未结 2 1313
夕颜
夕颜 2021-01-11 11:25

For sake of simplicity, let\'s assume I want to write an extension method for the type int? and int:

public static class IntExtentions
{
    public static in         


        
2条回答
  •  太阳男子
    2021-01-11 11:43

    Unfortunately not. You can make the int? (or whichever nullable type you are using) method call the non nullable method very easily though, so you don't need to duplicate any logic with 2 methods - e.g.

    public static class IntExtensions
    {
        public static int AddOne(this int? number)
        {
            return (number ?? 0).AddOne();
        }
    
        public static int AddOne(this int number)
        {
            return number + 1;
        }
    }
    

提交回复
热议问题