通过一个方法作为参数参数、方法

2023-09-07 03:28:12 作者:﹏淺Sè时光つ

我希望能够通过一个方法作为参数。

如..

  //真狡猾code
公共无效PassMeAMethod(字符串文本,法法)
{
  DoSomething的(文本);
  //调用该方法
  //方法一();
  美孚();
}

公共无效的methodA()
{
  //做的东西
}


公共无效的methodB()
{
  //做的东西
}

公共无效测试()
{
  PassMeAMethod(调用了methodA,的methodA)
  PassMeAMethod(调用的methodB的methodB)
}
 

我怎样才能做到这一点?

解决方案

您需要使用一个委托,这是重新presents的方法的特殊类。您可以定义自己的委托或使用内置者之一,但代表的签名必须要传递的方法相匹配。

定义自己的:

 公共委托INT MyDelegate(对象A);
 
day06

这个例子匹配,返回一个整数,需要一个对象引用作为参数的方法。

在你的榜样,两者的methodA和的methodB没有参数都返回void,所以我们可以使用内置的操作委托类。

下面就是你们的榜样修改:

 公共无效PassMeAMethod(字符串文本,操作方法)
{
  DoSomething的(文本);
  //调用该方法
  方法();
}

公共无效的methodA()
{
//做的东西
}


公共无效的methodB()
{
//做的东西
}

公共无效测试()
{
//明确
PassMeAMethod(调用了methodA,新的行动(的methodA));
//隐
PassMeAMethod(调用的methodB的methodB);

}
 

正如你所看到的,您可以使用委托类型明示或暗示的,哪个适合你的。

史蒂夫

I want to be able to pass a method as a parameter.

eg..

//really dodgy code
public void PassMeAMethod(string text, Method method)
{
  DoSomething(text);
  // call the method
  //method1();
  Foo();
}

public void methodA()
{
  //Do stuff
}


public void methodB()
{
  //Do stuff
}

public void Test()
{
  PassMeAMethod("calling methodA", methodA)
  PassMeAMethod("calling methodB", methodB)
}

How can I do this?

解决方案

You need to use a delegate, which is a special class that represents a method. You can either define your own delegate or use one of the built in ones, but the signature of the delegate must match the method you want to pass.

Defining your own:

public delegate int MyDelegate(Object a);

This example matches a method that returns an integer and takes an object reference as a parameter.

In your example, both methodA and methodB take no parameters have return void, so we can use the built in Action delegate class.

Here is your example modified:

public void PassMeAMethod(string text, Action method)
{
  DoSomething(text);
  // call the method
  method();    
}

public void methodA()
{
//Do stuff
}


public void methodB()
{
//Do stuff
}

public void Test()
{
//Explicit
PassMeAMethod("calling methodA", new Action(methodA));
//Implicit
PassMeAMethod("calling methodB", methodB);

}

As you can see, you can either use the delegate type explicitly or implicitly, whichever suits you.

Steve