我们通过sourceforge使用Andrew Davey 的 BindingListView<T>
类将集合绑定到 a并允许排序和过滤。 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>));
}