如何获取当前执行方法的接口实现类型?

huangapple go评论56阅读模式
英文:

How to get interface implementation type for currently executing method?

问题

您可以使用反射和方法信息来获取执行特定方法的接口实现类的信息,而无需修改每个实现或使用正则表达式来分析堆栈跟踪。以下是一种可能的方法:

try
{
    await _provider.Method();
    //_provider是声明为接口的
}
catch (Exception e)
{
    Type implementingType = _provider.GetType();
    // 获取执行Method方法的实际实现类的Type

    // 然后,您可以使用implementingType来记录或处理信息。
    // 例如,您可以将implementingType的名称记录到日志中以区分不同的实现。

    throw;
}

此代码将获取执行_provider.Method()的实际实现类的Type,并将其用于记录或处理信息,而无需修改每个实现或使用正则表达式来分析堆栈跟踪。

英文:

I have an interface with several implementations. The implementations and interface method call are in different packages if that matters.
I'm trying to catch the exception that may occur during the method execution and log it with the implementation name after the method call. The implementation name is used in logs to differentiate in timeseries.a

try
{
    await _provider.Method();
    //_provider is declared as interface
}
catch (Exception e)
{
    //here I'm planning to log things including implementation that threw the error
    throw;
}

Is there a way to find interface implementation class that is executing the method in question without applying some regex to stack trace or modifying method in question for each implementation?

I tried using reflection and method info, but am only getting either all implementations or just interface information.

答案1

得分: 1

如果您需要获取存储在 _provider 中的实例的实际类型,只需调用其上的 GetType 方法:

try
{
    await _provider.Method();
    // _provider 声明为接口
}
catch (Exception e)
{
   var actualType = _provider.GetType();
   var typeFullName = actualType.FullName; // 记录完整类型名称
   throw;
}
英文:

If you need to get the actual type of instance which is stored in the _provider just call GetType on it:

try
{
    await _provider.Method();
    //_provider is declared as interface
}
catch (Exception e)
{
   var actualType = _provider.GetType();
   var typeFullName = actualType.FullName; // log the full name
   throw;
}

huangapple
  • 本文由 发表于 2023年5月22日 22:44:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76307354.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定