programing

C#의 문자열에서 함수를 호출한다.

luckcodes 2022. 11. 7. 22:21

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

위의 코드를 사용하는 경우 호출되는 메서드에 액세스 수식자가 있어야 합니다.public비공개 메서드를 호출하려면BindingFlags파라미터, 예:BindingFlags.NonPublic | BindingFlags.Instance:

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

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

실제 인스턴스(이것)에 hello라는 이름의 메서드가 있다고 가정합니다.

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();
        }
    }
This code works in my console .Net application
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();
    }
}

약간의 접선 -- (filength!) 함수를 포함하는 식 문자열 전체를 해석하고 평가하려면 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기존 기능을 호출할 수 있습니다.

언급URL : https://stackoverflow.com/questions/540066/calling-a-function-from-a-string-in-c-sharp