目标是基于调用my方法的类型创建一个通用实例.
问题是,当从泛型调用时,StackFrame似乎只包含开放定义类型参数而不是封闭定义类型参数.如何从StackFrame中获取类型参数?与此问题类似.我想我的情况有所不同,因为Log.Debug是从一个封闭的方法调用的.
如果StackFrame不是正确的方法,除IoC以外的任何建议?此代码用于填写对我的Unity容器的引用不可用的情况.
using System;
using System.Reflection;
namespace ReflectionTest
{
public class Logger
{
private readonly string loggerName;
protected Logger(string loggerName) { this.loggerName = loggerName; }
public void Debug(string message) { Console.WriteLine(string.Format("{0} - {1}", loggerName, message)); }
}
public class Logger<T> : Logger
{
public Logger() : base(typeof(T).FullName) { }
}
public static class Log
{
public static void Debug(string message)
{
// Determine the calling function, and create a Logger<T> for it.
System.Diagnostics.StackFrame frame = new System.Diagnostics.StackFrame(1); …Run Code Online (Sandbox Code Playgroud)