我有一個動態方法,它需要一個DataRecord
並將數據映射到某個類型的對象。C#IL代碼將值添加到詞典
來源的對象具有Dictionary<string,object>
類型的詞典中,不能結合的DataRecord保存任何屬性。
但是,我似乎無法解決如何將這些添加到詞典。
我知道我必須在字典上撥打Emit(OpCodes.Callvirt, addMethod)
,但無論我嘗試什麼,我都無法弄清楚如何讓它工作。
public static Load CreateBuilder(IDataRecord dataRecord)
{
var dynamicBuilder = new DynamicBuilder<T>();
var method = new DynamicMethod("DynamicCreate", typeof(T), new[] { typeof(IDataRecord) }, typeof(T), true);
var generator = method.GetILGenerator();
var result = generator.DeclareLocal(typeof(T));
generator.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
generator.Emit(OpCodes.Stloc, result);
// Dictionary to store.
var dictType = typeof (Dictionary<string, object>);
var dict = typeof(T).GetProperty("CustomFields");
var addMethod = dictType.GetMethod("Add");
for (var i = 0; i < dataRecord.FieldCount; i++)
{
var propertyInfo = typeof(T).GetProperty(dataRecord.GetName(i));
var endIfLabel = generator.DefineLabel();
if (propertyInfo != null && propertyInfo.GetSetMethod() != null)
{
var attributes = propertyInfo.GetCustomAttributes(typeof(DbIgnore), true) as DbIgnore[];
if (attributes != null && attributes.Length > 0) continue;
bool isNullable = false;
if (propertyInfo.PropertyType.Name.ToLower().Contains("nullable"))
isNullable = true;
Type _type = dataRecord.GetFieldType(i);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Callvirt, IsDbNullMethod);
generator.Emit(OpCodes.Brtrue, endIfLabel);
generator.Emit(OpCodes.Ldloc, result);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Callvirt, GetValueMethod);
if (isNullable)
generator.Emit(OpCodes.Unbox_Any, GetNullableType(_type));
else
generator.Emit(OpCodes.Unbox_Any, _type);
//generator.Emit(OpCodes.Unbox_Any, dataRecord.GetFieldType(i));
generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod());
generator.MarkLabel(endIfLabel);
} else {
// How-To Add to Dictionary
}
}
generator.Emit(OpCodes.Ldloc, result);
generator.Emit(OpCodes.Ret);
return (Load)method.CreateDelegate(typeof(Load));
}
什麼不行? – Gabe 2011-05-12 01:00:57
我無法弄清楚如何引用對象上的Dictionary來調用addMethod。我可以創建一個新的dicitonary 'generator.DeclareLocal(dictType); generator.Emit(OpCodes.Newobj,dictType.GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Stloc_1);'併爲其成功添加值,但不知道如何在類上引用字典 – rqmedes 2011-05-12 01:15:49