extension method on type and nullable<type>

*爱你&永不变心* 提交于 2019-12-04 00:20:54

问题


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 int AddOne(this int? number)
    {
        var dummy = 0;
        if (number != null)
            dummy = (int)number;

        return dummy.AddOne();
    }

    public static int AddOne(this int number)
    {
        return number + 1;
    }
}

Can this be done using only 1 method?


回答1:


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;
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/742336/extension-method-on-type-and-nullabletype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!