C# function pointer?

前端 未结 5 1982
情话喂你
情话喂你 2020-12-25 12:40

I\'m having a problem with C#, I\'d like to get a pointer of a method in my code, but it seems impossible. I need the pointer of the method because I want to no-op it using

5条回答
  •  无人及你
    2020-12-25 12:45

    I know this is very old, but an example of something like a function pointer in C# would be like this:

    class Temp 
    {
       public void DoSomething() {}
       public void DoSomethingElse() {}
       public void DoSomethingWithAString(string myString) {}
       public bool GetANewCat(string name) { return true; }
    }
    

    ...and then in your main or wherever:

    var temp = new Temp();
    Action myPointer = null, myPointer2 = null;
    myPointer = temp.DoSomething;
    myPointer2 = temp.DoSomethingElse;
    

    Then to call the original function,

    myPointer();
    myPointer2();
    

    If you have arguments to your methods, then it's as simple as adding generic arguments to your Action:

    Action doItWithAString = null;
    doItWithAString = temp.DoSomethingWithAString;
    
    doItWithAString("help me");
    

    Or if you need to return a value:

    Func getACat = null;
    getACat = temp.GetANewCat;
    
    var gotIt = getACat("help me");
    

提交回复
热议问题