超载功能的简短方法?

时间:2015-08-11 02:13:59

标签: c# overloading

为什么要以更短的方式做到这一点? 我想过像void DoSth(int i) : DoSth(i, this);这样的东西。

class Foo
{

   void DoSth(int i)
   {
      DoSth(i, this);
   }

   static void DoSth(int i, Foo foo)
   {
      // do sth
   }

}

编辑:忘记static第二个功能

2 个答案:

答案 0 :(得分:6)

如果您使用的是C#6,则可以在类似方法的成员上使用表达式主体:

class Foo
{
    public DoSth(int i) => DoSth(i, this); 

    static void DoSth(int i, Foo foo)
    {
          // do sth
    }
}

答案 1 :(得分:3)

您可以使用可选参数:

class Foo
{    
   void DoSth(int i, Foo foo = null)
   {
      // do sth.. use "this" if "foo" is null
   }

}