我们即将在我的公司做一些反射器。IDictionary <obj, obj> to obj使用发射器
我需要一个FactoryClass,它可以通过对属性和字典键进行匹配来将IDictionary转换为obj。
我发现:
Dynamic object property populator (without reflection)
这个代码可以做我想做的,我想用这个代码,因为它是由使用的dotnet基本不使用他人的扩展来完成。
public class Populator<T>
{
private delegate T Load(Dictionary<string, object> properties);
private Load _handler;
private Populator() { }
public T Build(Dictionary<string, object> properties)
{
return _handler(properties);
}
public static Populator<T> CreateBuilder(Dictionary<string, object> properties)
{
//private static readonly MethodInfo getValueMethod = typeof(IDataRecord).GetMethod("get_Item", new [] { typeof(int) });
//private static readonly MethodInfo isDBNullMethod = typeof(IDataRecord).GetMethod("IsDBNull", new [] { typeof(int) });
Populator<T> dynamicBuilder = new Populator<T>();
...
当我测试这段代码时,出现错误。
public ICollection<object> GetKeys(IDictionary<object, object> products)
{
IDictionary<object, object> product = (IDictionary<object, object>)products.ElementAt(0).Value;
Dictionary<string, object> p = new Dictionary<string, object>();
foreach (KeyValuePair<object, object> item in product)
{
p.Add(item.Key.ToString(), item.Value);
}
Populator<ProductTest> builder = Populator<ProductTest>.CreateBuilder(p);
ProductTest obj = builder.Build(p); // error here
return null;
}
我这里
public class Populator<T>
{
private delegate T Load(Dictionary<string, object> properties);
private Load _handler;
private Populator() { }
public T Build(Dictionary<string, object> properties)
{
return _handler(properties); // Error: JIT Compiler encountered an internal limitation.
}
Wy的问题的错误是为什么,以及如何解决呢? 堆栈跟踪中没有额外的东西。
//丹尼斯
的问题肯定是产生了'Load'委托的代码,但你没有张贴的一部分,所以我们不能真正帮助你... – 2010-09-30 12:25:01
这是一个利益例外,但它是完全不可能用所提供的代码重新编制它。很不清楚_handler是如何初始化的。如果你使用任何Reflection.Emit,那么你只是搞砸了IL。 – 2010-09-30 12:34:52