【发布时间】:2011-09-28 16:03:48
【问题描述】:
目标是基于调用我的方法的类型创建一个通用实例。
问题在于,当从泛型调用时,StackFrame 似乎只包含开放定义类型参数,而不是封闭定义类型参数。如何从 StackFrame 获取类型参数?类似于this question。我想我的情况有所不同,因为 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);
MethodBase method = frame.GetMethod();
/// When method is from a generic class,
/// the method.ReflectedType definintion is open: Type.ContainsGenericParameters is true
/// How do I get the generic parameters of method.ReflectedType so
/// Activator.CreateInstance() will not throw?
Type logType = typeof(Logger<>);
Type constructed = logType.MakeGenericType(new Type[] { method.ReflectedType });
Logger logger = (Logger)Activator.CreateInstance(constructed);
logger.Debug(message);
}
}
public class MyBase<T>
{
public void Run()
{
Log.Debug("Run Generic"); // throws on Activator.CreateInstance()
}
}
class Program
{
static void Works()
{
Log.Debug("Run NonGeneric"); // works
}
static void DoesNotWork()
{
MyBase<int> b = new MyBase<int>();
b.Run();
}
static void Main(string[] args)
{
Works();
DoesNotWork();
}
}
}
【问题讨论】:
标签: c# .net generics reflection