在扩展方法中获取扩展方法的参数

时间:2015-11-12 01:18:29

标签: c# extension-methods static-methods

假设我有方法:

public int Method(string param1, string param2)
{
     return 0;
}

我有扩展方法

public static int Extend(this int mhd, string param1, string param2)
{
     return mhd;
}

我会称之为

int N = Method("param1","param2").Extend("param1","param2");

但是有了这个,我不得不两次定义参数。我想知道有没有办法得到这样的扩展方法参数:

public static int Extend(this int mhd)
{
     var params = this.Parameters;
     return mhd;
}

1 个答案:

答案 0 :(得分:0)

  

但是有了这个,我不得不两次定义参数。我想知道有没有办法得到这样的扩展方法参数:

没有。扩展方法的第一个参数始终是方法的类型。 声明中需要此参数,因此如果要传递任何内容,则必须声明该第二个参数。

为什么不把所有代码都放在一个方法中?

你可以反转方法依赖吗?换句话说就是这样:

int N = 0.Extend(Method("param1","param2"));    

或者,像这样:

public int Method ( int mhd, string one, string two ) {
   // do stuff...

  return mhd.Extend ( one, two );
}