有人能告诉我如何在 C#中实施按名称呼叫?
答案 0 :(得分: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
会记住结果,以便重复访问不必重新评估函数。
答案 1 :(得分:2)
您可以使用Reflection执行此操作:
using System; using System.Reflection; class CallMethodByName { string name; CallMethodByName (string name) { this.name = name; } public void DisplayName() // method to call by name { Console.WriteLine (name); // prove we called it } static void Main() { // Instantiate this class CallMethodByName cmbn = new CallMethodByName ("CSO"); // Get the desired method by name: DisplayName MethodInfo methodInfo = typeof (CallMethodByName).GetMethod ("DisplayName"); // Use the instance to call the method without arguments methodInfo.Invoke (cmbn, null); } }
答案 2 :(得分: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;
}
答案 3 :(得分:1)
如果您的意思是this,那么我认为最接近的同等人就是代表。
答案 4 :(得分:0)
为什么不使用
Microsoft.VisualBasic.Interaction.CallByName