リフレクションを使用して、現在実行中のメソッドの名前を見つけることはできますか?
-
09-06-2019 - |
質問
タイトルにあるように、リフレクションにより、現在実行中のメソッドの名前が得られますか。
ハイゼンベルク問題のせいで、私はそうではないと推測する傾向があります。現在のメソッドを変更せずに、現在のメソッドを通知するメソッドを呼び出すにはどうすればよいでしょうか?しかし、誰かが私が間違っていることを証明してくれることを願っています。
アップデート:
- パート2:これを使用して、プロパティのコード内部を調べることもできますか?
- パート 3:パフォーマンスはどうなるでしょうか?
最終結果
MethodBase.GetCurrentMethod() について学びました。また、スタック トレースを作成できるだけでなく、必要に応じて必要なフレームだけを作成できることも学びました。
これをプロパティ内で使用するには、.Substring(4) を使用して「set_」または「get_」を削除するだけです。
解決
.NET 4.5 以降では、以下も使用できます [発信者のメンバー名]
例:プロパティ セッター (パート 2 への回答):
protected void SetProperty<T>(T value, [CallerMemberName] string property = null)
{
this.propertyValues[property] = value;
OnPropertyChanged(property);
}
public string SomeProperty
{
set { SetProperty(value); }
}
コンパイラは呼び出しサイトで一致する文字列リテラルを提供するため、基本的にパフォーマンスのオーバーヘッドはありません。
他のヒント
System.Reflection.MethodBase.GetCurrentMethod().Name;
http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx
Lex が提供したスニペットは少し長かったので、まったく同じ手法を使用した人が他にいないため、重要な部分を指摘します。
string MethodName = new StackFrame(0).GetMethod().Name;
これにより、同じ結果が返されるはずです。 MethodBase.GetCurrentMethod().Name ただし、インデックス 1 を使用して独自のメソッドでこれを一度実装できるため、それでも指摘する価値はあります。 前の メソッドを作成し、さまざまなプロパティから呼び出します。また、スタック トレース全体ではなく 1 つのフレームのみを返します。
private string GetPropertyName()
{ //.SubString(4) strips the property prefix (get|set) from the name
return new StackFrame(1).GetMethod().Name.Substring(4);
}
それもワンライナーです ;)
空のコンソール プログラムの Main メソッド内でこれを試してください。
MethodBase method = MethodBase.GetCurrentMethod();
Console.WriteLine(method.Name);
コンソール出力:
Main
はい、間違いなく。
オブジェクトを操作したい場合は、実際に次のような関数を使用します。
public static T CreateWrapper<T>(Exception innerException, params object[] parameterValues) where T : Exception, new()
{
if (parameterValues == null)
{
parameterValues = new object[0];
}
Exception exception = null;
StringBuilder builder = new StringBuilder();
MethodBase method = new StackFrame(2).GetMethod();
ParameterInfo[] parameters = method.GetParameters();
builder.AppendFormat(CultureInfo.InvariantCulture, ExceptionFormat, new object[] { method.DeclaringType.Name, method.Name });
if ((parameters.Length > 0) || (parameterValues.Length > 0))
{
builder.Append(GetParameterList(parameters, parameterValues));
}
exception = (Exception)Activator.CreateInstance(typeof(T), new object[] { builder.ToString(), innerException });
return (T)exception;
}
この行:
MethodBase method = new StackFrame(2).GetMethod();
スタック フレームをたどって呼び出しメソッドを見つけます。次に、リフレクションを使用して、汎用エラー報告関数に渡されるパラメーター情報値を取得します。現在のメソッドを取得するには、代わりに現在のスタック フレーム (1) を使用するだけです。
他の人が現在のメソッド名について述べているように、次のメソッドも使用できます。
MethodBase.GetCurrentMethod()
私はスタックをウォークすることを好みます。そのメソッドを内部的に見ても、とにかく StackCrawlMark を作成するだけだからです。スタックに直接アドレス指定する方が私には明確に思えます
4.5 以降では、メソッド パラメーターの一部として [CallerMemberNameAttribute] を使用して、メソッド名の文字列を取得できるようになりました。これは、一部のシナリオでは役立つかもしれません (ただし、実際には上記の例が当てはまります)。
public void Foo ([CallerMemberName] string methodName = null)
これは主に、以前はイベント コード全体に文字列が散らばっていた INotifyPropertyChanged サポートに対する解決策であるようです。
メソッド名を取得する方法の比較 -- 任意のタイミング構造 LinqPad の場合:
コード
void Main()
{
// from http://blogs.msdn.com/b/webdevelopertips/archive/2009/06/23/tip-83-did-you-know-you-can-get-the-name-of-the-calling-method-from-the-stack-using-reflection.aspx
// and https://stackoverflow.com/questions/2652460/c-sharp-how-to-get-the-name-of-the-current-method-from-code
var fn = new methods();
fn.reflection().Dump("reflection");
fn.stacktrace().Dump("stacktrace");
fn.inlineconstant().Dump("inlineconstant");
fn.constant().Dump("constant");
fn.expr().Dump("expr");
fn.exprmember().Dump("exprmember");
fn.callermember().Dump("callermember");
new Perf {
{ "reflection", n => fn.reflection() },
{ "stacktrace", n => fn.stacktrace() },
{ "inlineconstant", n => fn.inlineconstant() },
{ "constant", n => fn.constant() },
{ "expr", n => fn.expr() },
{ "exprmember", n => fn.exprmember() },
{ "callermember", n => fn.callermember() },
}.Vs("Method name retrieval");
}
// Define other methods and classes here
class methods {
public string reflection() {
return System.Reflection.MethodBase.GetCurrentMethod().Name;
}
public string stacktrace() {
return new StackTrace().GetFrame(0).GetMethod().Name;
}
public string inlineconstant() {
return "inlineconstant";
}
const string CONSTANT_NAME = "constant";
public string constant() {
return CONSTANT_NAME;
}
public string expr() {
Expression<Func<methods, string>> ex = e => e.expr();
return ex.ToString();
}
public string exprmember() {
return expressionName<methods,string>(e => e.exprmember);
}
protected string expressionName<T,P>(Expression<Func<T,Func<P>>> action) {
// https://stackoverflow.com/a/9015598/1037948
return ((((action.Body as UnaryExpression).Operand as MethodCallExpression).Object as ConstantExpression).Value as MethodInfo).Name;
}
public string callermember([CallerMemberName]string name = null) {
return name;
}
}
結果
反射反射
スタックトレーススタックトレース
インライン定数インライン定数
絶え間ない絶え間ない
式e => e.expr()
エクスプメンバーエクスプメンバー
発信者メンバー主要
Method name retrieval: (reflection) vs (stacktrace) vs (inlineconstant) vs (constant) vs (expr) vs (exprmember) vs (callermember)
154673 ticks elapsed ( 15.4673 ms) - reflection
2588601 ticks elapsed (258.8601 ms) - stacktrace
1985 ticks elapsed ( 0.1985 ms) - inlineconstant
1385 ticks elapsed ( 0.1385 ms) - constant
1366706 ticks elapsed (136.6706 ms) - expr
775160 ticks elapsed ( 77.516 ms) - exprmember
2073 ticks elapsed ( 0.2073 ms) - callermember
>> winner: constant
注意してください。 expr
そして callermember
方法はまったく「正しく」ありません。そして、そこには次の繰り返しが見られます。 関連するコメント そのリフレクションはスタックトレースよりも最大 15 倍高速です。
編集:MethodBase は、(呼び出しスタック全体ではなく) 現在のメソッドを取得するためのより良い方法であると考えられます。ただし、インライン化についてはまだ懸念があります。
メソッド内で StackTrace を使用できます。
StackTrace st = new StackTrace(true);
そしてフレームを見てみましょう:
// The first frame will be the method you want (However, see caution below)
st.GetFrames();
ただし、メソッドがインライン化されている場合は、想定しているメソッドの内部に存在しないことに注意してください。属性を使用してインライン化を防ぐことができます。
[MethodImpl(MethodImplOptions.NoInlining)]
簡単な対処方法は次のとおりです。
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
System.Reflection が using ブロックに含まれている場合:
MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name;
これはどうでしょうか:
StackFrame frame = new StackFrame(1);
frame.GetMethod().Name; //Gets the current method name
MethodBase method = frame.GetMethod();
method.DeclaringType.Name //Gets the current class name
を作成することでそれを取得できるはずだと思います スタックトレース. 。または、@としてエッジ そして @ラース・メーラム MethodBase について言及します。GetCurrentメソッド()
メソッドの文字列名だけが必要な場合は、式を使用できます。見る http://joelabrahamsson.com/entry/getting-property-and-method-names-using-static-reflection-in-c-sharp
これを試して...
/// <summary>
/// Return the full name of method
/// </summary>
/// <param name="obj">Class that calls this method (use Report(this))</param>
/// <returns></returns>
public string Report(object obj)
{
var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType;
if (reflectedType == null) return null;
var i = reflectedType.FullName;
var ii = new StackTrace().GetFrame(1).GetMethod().Name;
return string.Concat(i, ".", ii);
}
単純な静的クラスでこれを実行しました。
using System.Runtime.CompilerServices;
.
.
.
public static class MyMethodName
{
public static string Show([CallerMemberName] string name = "")
{
return name;
}
}
次に、コード内で次のようにします。
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = MyMethodName.Show();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = MyMethodName.Show();
}