【发布时间】:2012-05-22 09:05:16
【问题描述】:
我们通过sourceforge 使用Andrew Davey's BindingListView<T> 类将集合绑定到DataGridView 并允许排序和过滤。
这适用于普通收藏。然而,在一种情况下,我们绑定到的集合是一个接口类型,如果我们尝试对其进行排序,则会出现此错误:
Invalid type owner for DynamicMethod
这个错误在 Andrew Davies 的代码中很深,所以我们很难知道从哪里开始。
private static Comparison<T> BuildValueTypeComparison(PropertyInfo pi, ListSortDirection direction)
{
MethodInfo getMethod = pi.GetGetMethod();
Debug.Assert(getMethod != null);
DynamicMethod dm = new DynamicMethod("Get" + pi.Name, typeof(int), new Type[] { typeof(T), typeof(T) }, typeof(T), true);
//^^^ ======== Here's the line reporting the error=========== ^^^
ILGenerator il = dm.GetILGenerator();
// Get the value of the first object's property.
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Call, getMethod, null);
// Box the value type
il.Emit(OpCodes.Box, pi.PropertyType);
// Get the value of the second object's property.
il.Emit(OpCodes.Ldarg_1);
il.EmitCall(OpCodes.Call, getMethod, null);
// Box the value type
il.Emit(OpCodes.Box, pi.PropertyType);
// Cast the first value to IComparable and call CompareTo,
// passing the second value as the argument.
il.Emit(OpCodes.Castclass, typeof(IComparable));
il.EmitCall(OpCodes.Call, typeof(IComparable).GetMethod("CompareTo"), null);
// If descending then multiply comparison result by -1
// to reverse the ordering.
if (direction == ListSortDirection.Descending)
{
il.Emit(OpCodes.Ldc_I4_M1);
il.Emit(OpCodes.Mul);
}
// Return the result of the comparison.
il.Emit(OpCodes.Ret);
// Create the delegate pointing at the dynamic method.
return (Comparison<T>)dm.CreateDelegate(typeof(Comparison<T>));
}
【问题讨论】:
-
我刚刚下载了库,并修改了示例应用程序,使其绑定到接口而不是具体类型,并且工作正常;所以它不能只是你绑定到一个接口的事实。您能否发布一个展示此行为的最小接口和实现类,因为这绝对是特定于实现的?
-
好的,我收回,你正在使用
AggregateBindingListView,它确实抛出了。