[C#] C #에서 문자열에서 함수 호출

PHP에서 다음과 같이 전화를 걸 수 있다는 것을 알고 있습니다.

$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }

.Net에서 가능합니까?



답변

예. 반사를 사용할 수 있습니다. 이 같은:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);


답변

리플렉션을 사용하여 동적 메소드 호출을 수행하여 클래스 인스턴스의 메소드를 호출 할 수 있습니다.

실제 인스턴스에 hello라는 메소드가 있다고 가정합니다 (this).

string methodName = "hello";

//Get the method information using the method info class
 MethodInfo mi = this.GetType().GetMethod(methodName);

//Invoke the method
// (null- no parameter for the method call
// or you can pass the array of parameters...)
mi.Invoke(this, null);


답변

class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(MyReflectionClass);
            MethodInfo method = type.GetMethod("MyMethod");
            MyReflectionClass c = new MyReflectionClass();
            string result = (string)method.Invoke(c, null);
            Console.WriteLine(result);

        }
    }

    public class MyReflectionClass
    {
        public string MyMethod()
        {
            return DateTime.Now.ToString();
        }
    }


답변

약간의 접선-(중첩 된) 함수를 포함하는 전체 표현식 문자열을 구문 분석하고 평가하려면 NCalc ( http://ncalc.codeplex.com/ 및 nuget)를 고려하십시오.

전의. 프로젝트 문서에서 약간 수정되었습니다.

// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);

// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
        if (name == "MyFunction")
            args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
    };

// confirm it worked
Debug.Assert(19 == e.Evaluate());

EvaluateFunction델리게이트 내에서 기존 함수를 호출합니다.


답변

사실 Windows Workflow 4.5에서 작업 중이며 상태 머신에서 메서드로 대리자를 성공하지 않고 전달하는 방법을 찾았습니다. 내가 찾은 유일한 방법은 대리자로 전달하려는 메서드 이름으로 문자열을 전달하고 문자열을 메서드 내부의 대리자로 변환하는 것입니다. 아주 좋은 답변입니다. 감사. 이 링크를 확인하십시오 https://msdn.microsoft.com/en-us/library/53cz7sc6(v=vs.110).aspx


답변

이 코드는 내 콘솔 .Net 응용 프로그램에서 작동합니다.

class Program
{
    static void Main(string[] args)
    {
        string method = args[0]; // get name method
        CallMethod(method);
    }
    
    public static void CallMethod(string method)
    {
        try
        {
            Type type = typeof(Program);
            MethodInfo methodInfo = type.GetMethod(method);
            methodInfo.Invoke(method, null);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            Console.ReadKey();
        }
    }
    
    public static void Hello()
    {
        string a = "hello world!";
        Console.WriteLine(a);
        Console.ReadKey();
    }
}


답변

C #에서는 대리자를 함수 포인터로 만들 수 있습니다. 사용법에 대한 정보는 다음 MSDN 기사를 확인하십시오.http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx

    public static void hello()
    {
        Console.Write("hello world");
    }

   /* code snipped */

    public delegate void functionPointer();

    functionPointer foo = hello;
    foo();  // Writes hello world to the console.