英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论