5

谁能告诉我如何在C#中实现按名称调用

4

5 回答 5

9

传递一个 lambda 函数而不是一个值。C# 被急切地评估,以便推迟执行,以便每个站点重新评估提供的参数,您需要将参数包装在函数中。

int blah = 1;

void Foo(Func<int> somethingToDo)  {
  int result1 = somethingToDo(); // result1 = 100

  blah = 5;
  int result2 = somethingToDo(); // result = 500
}

Foo(() => blah * 100);

如果您在 .NET 4.0 中,则 可以使用Lazy类来获得类似(但不相同)的效果。Lazy记住结果,以便重复访问不必重新评估函数。

于 2010-10-25T22:09:12.587 回答
2

您可以使用反射来做到这一点:

使用系统;
使用 System.Reflection;

类 CallMethodByName
{
   字符串名称;

   CallMethodByName(字符串名称)
   {
      this.name = 名称;
   }

   public void DisplayName() // 按名称调用的方法
   {
      Console.WriteLine(名称);// 证明我们调用了它
   }

   静态无效主要()
   {
      // 实例化这个类
      CallMethodByName cmbn = new CallMethodByName ("CSO");

      // 通过名称获取所需的方法:DisplayName
      方法信息方法信息 =
         typeof (CallMethodByName).GetMethod ("DisplayName");

      // 使用实例调用不带参数的方法
      methodInfo.Invoke (cmbn, null);
   }
}
于 2010-10-25T21:58:57.987 回答
2
public enum CallType
{
/// <summary>
/// Gets a value from a property.
/// </summary>
Get,
/// <summary>
/// Sets a value into a property.
/// </summary>
Let,
/// <summary>
/// Invokes a method.
/// </summary>
Method,
/// <summary>
/// Sets a value into a property.
/// </summary>
Set
}

/// <summary>
/// Allows late bound invocation of
/// properties and methods.
/// </summary>
/// <param name="target">Object implementing the property or method.</param>
/// <param name="methodName">Name of the property or method.</param>
/// <param name="callType">Specifies how to invoke the property or method.</param>
/// <param name="args">List of arguments to pass to the method.</param>
/// <returns>The result of the property or method invocation.</returns>
public static object CallByName(object target, string methodName, CallType callType, params object[] args)
{
  switch (callType)
  {
    case CallType.Get:
      {
        PropertyInfo p = target.GetType().GetProperty(methodName);
        return p.GetValue(target, args);
      }
    case CallType.Let:
    case CallType.Set:
      {
        PropertyInfo p = target.GetType().GetProperty(methodName);
        p.SetValue(target, args[0], null);
        return null;
      }
    case CallType.Method:
      {
        MethodInfo m = target.GetType().GetMethod(methodName);
        return m.Invoke(target, args);
      }
  }
  return null;
}
于 2014-12-18T03:11:01.307 回答
1

为什么不使用

Microsoft.VisualBasic.Interaction.CallByName
于 2012-04-05T14:53:33.483 回答
1

如果你的意思是这个,那么我认为最接近的等价物是代表。

于 2010-10-25T22:00:21.363 回答