1

在我的程序中,我想获取一个函数作为参数,并从另一个函数中调用它。可以吗?
谢谢你

4

5 回答 5

4

当然,您可以只接受 aDelegate并使用Delegate.DynamicInvokeor Delegate.Method.Invoke。除非提供更多信息,否则这将回答您的问题。

因此:

class Foo {
    public void M(Delegate d) {
        d.DynamicInvoke();
    }
}

Action action = () => Console.WriteLine("Hello, world!");
var foo = new Foo();
foo.M(action);
于 2011-08-15T18:35:14.583 回答
3

http://msdn.microsoft.com/en-us/library/ms173172(v=vs.80).aspx

于 2011-08-15T18:32:05.023 回答
0

或者您可以使用 lambda 表达式。仍然委托,但编码速度更快。

private static void Main(string[] args)
{
    NoReturnValue((i) =>
        {
            // work here...
            Console.WriteLine(i);
        });
    var value = ReturnSometing((i) =>
        {
            // work here...
            return i > 0;
        });
}

private static void NoReturnValue(Action<int> foo)
{
    // work here to determind input to foo
    foo(0);
}

private static T ReturnSometing<T>(Func<int, T> foo)
{
    // work here to determind input to foo
    return foo(0);
}
于 2011-08-15T18:39:06.900 回答
-2

一个例子:

Action logEntrance = () => Debug.WriteLine("Entered");
UpdateUserAccount(logEntrance);

public void UpdateUserAccount(
           IUserAccount account, 
           Action logEntrance)
{
   if (logEntrance != null)
   {
      logEntrance();
   }
}
于 2011-08-15T18:35:29.333 回答
-2
  • 用于Func在保持类型安全的同时使用任意函数。

    这可以通过内置的 Func 泛型类来完成:

    给定一个具有以下签名的方法(在这种情况下,它接受一个 int 并返回一个 bool):

    void Foo(Func<int, bool> fun);
    

    你可以这样称呼它:

    Foo(myMethod);    
    Foo(x => x > 5);  
    

    您可以将任意函数分配给 Func 实例:

    var f = new Func<int, int, double>((x,y) => { return x/y; });
    

    您可以将其传递给f以后可以使用的地方:

    Assert.AreEqual(2.0, f(6,3));  // ;-) I wonder if that works
    

    请参阅此处了解更多信息。

  • 当你真的不知道参数时使用反射,但你愿意付出代价在运行时调查它们。

    在此处阅读有关此内容。您将传递MemberInfo. 您可以查询其参数以动态发现其数量和类型。

  • 使用dynamic完全自由。没有类型安全。

    而在 C# 4.0 中,您现在有了dynamic关键字。

    public void foo(dynamic f) {
      f.Hello();
    }
    
    public class Foo {
      public void Hello() { Console.WriteLine("Hello World");}
    }
    
    [Test]
    public void TestDynamic() {
      dynamic d = new Foo();
      foo(d);
    }
    

    在这里查看更多信息。

于 2011-08-15T18:36:48.283 回答