誰かがC#で名前による呼び出しを実装する方法を教えてもらえますか?
6591 次
5 に答える
9
値の代わりにラムダ関数を渡します。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 = name; } public void DisplayName()//名前で呼び出すメソッド {{ Console.WriteLine(名前); //それを呼んだことを証明する } static void Main() {{ //このクラスをインスタンス化します CallMethodByName cmbn = new CallMethodByName( "CSO"); //目的のメソッドを名前で取得します:DisplayName MethodInfo methodInfo = 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
あなたがこれを意味するならば、私は最も近い同等物は代表者であると思います。
于 2010-10-25T22:00:21.363 に答える
1
使ってみませんか
Microsoft.VisualBasic.Interaction.CallByName
于 2012-04-05T14:53:33.483 に答える