Прочитать на английском

Поделиться через


MethodBase.GetCurrentMethod Метод

Определение

Возвращает объект MethodBase, представляющий выполняющийся в текущий момент метод.

public static System.Reflection.MethodBase? GetCurrentMethod();
public static System.Reflection.MethodBase GetCurrentMethod();

Возвращаемое значение

GetCurrentMethod() — это статический метод, который вызывается из выполняющегося метода и возвращает сведения об этом методе.

Объект MethodBase, представляющий выполняющийся в текущий момент метод.

Исключения

Этот элемент был вызван при помощи механизма позднего связывания.

Примеры

В следующем примере определяются два типа. Первый является неуниверсивным классом , TestClassвключает конструктор, метод с именем GetValueи свойство чтения и записи с именем GetValue. Второй является универсальным классом с именем TestClass<T> , который включает конструктор, GetValue метод и универсальный метод , ConvertValue<Y>. Каждый конструктор, метод и метод доступа свойства включает вызов GetCurrentMethod метода .

using System;
using System.Reflection;

public class Example
{
   public static void Main()
   {
      var t = new TestClass();  
      Console.WriteLine(t.GetValue());
      t.Value = 10;
      Console.WriteLine(t.Value);
      Console.WriteLine();
      
      var tg =new Test<int>(200);
      Console.WriteLine(tg.GetValue());
      var b = tg.ConvertValue<Byte>();
      Console.WriteLine("{0} -> {1} ({2})", tg.GetValue().GetType().Name,
                        b, b.GetType().Name);
   }
}        

public class TestClass
{
   private Nullable<int> _value;
   
   public TestClass()
   {
      MethodBase m = MethodBase.GetCurrentMethod();
      Console.WriteLine("Executing {0}.{1}", 
                        m.ReflectedType.Name, m.Name);
   }
   
   public TestClass(int value)
   {
      MethodBase m = MethodBase.GetCurrentMethod();
      Console.WriteLine("Executing {0}.{1}", 
                        m.ReflectedType.Name, m.Name);
      _value = value;
   }
   
   public int Value
   {  
      get {
         MethodBase m = MethodBase.GetCurrentMethod();
         Console.WriteLine("Executing {0}.{1}", 
                           m.ReflectedType.Name, m.Name);
         return _value.GetValueOrDefault();
      }
      set {
         MethodBase m = MethodBase.GetCurrentMethod();
         Console.WriteLine("Executing {0}.{1}", 
                           m.ReflectedType.Name, m.Name);
         _value = value;
      }
   }
   
   public int GetValue()
   {
      MethodBase m = MethodBase.GetCurrentMethod();
      Console.WriteLine("Executing {0}.{1}", 
                        m.ReflectedType.Name, m.Name);
      return this.Value;
   }
}

public class Test<T>
{
   private T value;
   
   public Test(T value)
   {
      MethodBase m = MethodBase.GetCurrentMethod();
      Console.WriteLine("Executing {0}.{1}", 
                        m.ReflectedType.Name, m.Name);
      this.value = value;
   }
   
   public T GetValue()
   {
      MethodBase m = MethodBase.GetCurrentMethod();
      Console.WriteLine("Executing {0}.{1}", 
                        m.ReflectedType.Name, m.Name);
      return value;
   }
   
   public Y ConvertValue<Y>() 
   {
      MethodBase m = MethodBase.GetCurrentMethod();
      Console.WriteLine("Executing {0}.{1}", 
                        m.ReflectedType.Name, m.Name);
      Console.Write("      Generic method: {0}, definition: {1}, Args: ", 
                        m.IsGenericMethod, m.IsGenericMethodDefinition);
      if (m.IsGenericMethod) {
         foreach (var arg in m.GetGenericArguments())
            Console.Write("{0} ", arg.Name);
      }
      Console.WriteLine();
      try {
         return (Y) Convert.ChangeType(value, typeof(Y));
      }
      catch (OverflowException) {
         throw; 
      }   
      catch (InvalidCastException) {
         throw;
      }   
   }   
}
// The example displays the following output:
//       Executing TestClass..ctor
//       Executing TestClass.GetValue
//       Executing TestClass.get_Value
//       0
//       Executing TestClass.set_Value
//       Executing TestClass.get_Value
//       10
//       
//       Executing Test`1..ctor
//       Executing Test`1.GetValue
//       200
//       Executing Test`1.ConvertValue
//             Generic method: True, definition: True, Args: Y
//       Executing Test`1.GetValue
//       Int32 -> 200 (Byte)

Комментарии

Если выполняемый в данный момент метод определен для универсального типа, объект , MethodInfo возвращаемый методом GetCurrentMethod , получается из определения универсального типа (то есть MethodBase.ContainsGenericParameters возвращает true). Таким образом, он не отражает аргументы типа, которые использовались при вызове метода . Например, если метод M() определен для универсального типа C<T> (C(Of T) в Visual Basic) и GetCurrentMethod вызывается из C<string>.M(), то GetCurrentMethod возвращает ( C<T>.M()C(Of T).M() в Visual Basic).

Если текущий выполняемый метод является универсальным методом, GetCurrentMethod возвращает определение универсального метода. Если универсальный метод определен для универсального типа, MethodInfo объект получается из определения универсального типа.

Применяется к

Продукт Версии
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1