extension method on type and nullable

后端 未结 2 1289
夕颜
夕颜 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:45

    No you cannot. This can be verified experimentally by compiling the following code

    public static class Example {
      public static int Test(this int? source) {
        return 42;
      }
      public void Main() {
        int v1 = 42;
        v1.Test();  // Does not compile
      }
    }
    

    You will need to write an extension method for each type (nullable and not nullable) if you want it used on both types.

提交回复
热议问题