- C# code
public class TypeChange<Entity> { /// <summary> /// 声明一个泛型委托 /// </summary> /// <param name="Entity"></param> /// <returns></returns> private delegate SqlParameter[] Load(Entity Entity); /// <summary> /// 创建实体的委托对象 /// </summary> private Load handler; /// <summary> /// 私有化构造方法 /// </summary> private TypeChange() { } public SqlParameter[] Builder(Entity entity) { return handler(entity); } public static TypeChange<Entity> TypeChanger() { TypeChange<Entity> changer = new TypeChange<Entity>(); DynamicMethod method = new DynamicMethod("DynamicChangeType", typeof(Entity), new Type[] { typeof(SqlParameter[]) }, typeof(Entity), true); ILGenerator generator = method.GetILGenerator(); LocalBuilder result = generator.DeclareLocal(typeof(SqlParameter[])); int count= typeof(Entity).GetProperties().Length; SqlParameter[] sp=new SqlParameter[count]; generator.Emit(OpCodes.Ldc_I4, count); generator.Emit(OpCodes.Newarr, typeof(SqlParameter[])); generator.Emit(OpCodes.Stloc, result); for (int i = 0; i < count; i++) { PropertyInfo propertyInfo = typeof(Entity).GetProperties()[i]; if (propertyInfo != null && propertyInfo.GetGetMethod() != null) { //sp.set(i,new SqlParameter("@属性名",entity.getvalue())) generator.Emit(OpCodes.Ldloc,result); generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldarg, "@"+propertyInfo.Name); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Callvirt, propertyInfo.GetGetMethod()); generator.Emit(OpCodes.Newobj, typeof(SqlParameter).GetConstructor(new Type[] { typeof(string), typeof(object) })); generator.Emit(OpCodes.Callvirt, typeof(SqlParameter[]).GetMethod("Set")); } } generator.Emit(OpCodes.Ldloc, result); generator.Emit(OpCodes.Ret); return changer; } }
------解决方案--------------------------------------------------------
报啥错了?
------解决方案--------------------------------------------------------