开发者

C# - passing a function of unknown type to another function and calling it

In my program i'm suppose to get a function as开发者_运维技巧 a parameter, and call it from within another function. can it be done?

thank you


Sure, you could just take in a Delegate and utilize Delegate.DynamicInvoke or Delegate.Method.Invoke. Barring more information, this answers your question.

Thus:

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

Action action = () => Console.WriteLine("Hello, world!");
var foo = new Foo();
foo.M(action);


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


or you can use lambda expressions. delegate still, but faster to code.

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


An example:

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

public void UpdateUserAccount(
           IUserAccount account, 
           Action logEntrance)
{
   if (logEntrance != null)
   {
      logEntrance();
   }
}


  • Use Func to use arbitrary functions while preserving type safety.

    This can be done with the built-in Func generic class:

    Given a method with the following signature (in this case, it takes an int and returns a bool):

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

    You can call it like this:

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

    You can assign arbitrary functions to a Func instance:

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

    And you can pass that f around where it can be used later:

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

    See here for more information.

  • Use Reflection when you really don't know the parameters, but you are willing to pay the cost to investigate them at run time.

    Read about this here. You will be passing around instances of MemberInfo. You can query its parameters to dynamically discover their number and type.

  • use dynamic for complete freedom. There is no type safety.

    And in C# 4.0, you now have the dynamic keyword.

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

    See more on this here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜