Dot-Net

從getter/setter的MethodInfo中找到宿主PropertyInfo

  • February 6, 2009

我在執行時使用反射進行了一些類型分析。如果我有一個 MethodInfo 實例,我如何確定這是一個“真實”方法還是一個屬性的 getter/setter 方法?如果它是一個屬性,我怎樣才能找到它的託管 PropertyInfo 回來?

Ecma 335 指定(但不要求)編譯器使用 get_/set_ 前綴(第 22.28 章)。我不知道任何違反該建議的語言。讓它變得簡單:

public static PropertyInfo GetPropFromMethod(Type t, MethodInfo method) {
 if (!method.IsSpecialName) return null;
 return t.GetProperty(method.Name.Substring(4), 
   BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
}

好吧,getter 和 setter 背後的方法“真正的”方法。

重新跟踪到一個屬性 - 模式(返回與採用 1 個參數)將有助於縮小範圍 - 但您必須在每個上呼叫 GetGetMethod/GetSetMethod 才能找到該屬性。

您可能可以嘗試( Nameless get__/set__) - 但這感覺很脆弱。這是較長的版本(不使用Name):

static PropertyInfo GetProperty(MethodInfo method)
{
   bool takesArg = method.GetParameters().Length == 1;
   bool hasReturn = method.ReturnType != typeof(void);
   if (takesArg == hasReturn) return null;
   if (takesArg)
   {
       return method.DeclaringType.GetProperties()
           .Where(prop => prop.GetSetMethod() == method).FirstOrDefault();
   }
   else
   {
       return method.DeclaringType.GetProperties()
           .Where(prop => prop.GetGetMethod() == method).FirstOrDefault();
   }
}

引用自:https://stackoverflow.com/questions/520138