我們即將在我的公司做一些反射器。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