我正在尝试初始化DataEditor<Student>的对象,其中我的DataEditor<T>类实现interface IDataEditor<T> where T : IEditableObject

DataEditor<Student> editor = GetEditorFor(student);

在运行时,我得到一个TypeLoadException的说法:
Namespace.IDataEditor`1 [T]上的GenericArguments [0],'Namespace.Data.Student'违反了类型参数'T'的约束。异常发生在上面的行中,甚至还没有进入GetEditorFor方法内部。

对T的唯一约束是IEditableObject,我的Student类清楚地实现了它(我仔细检查了接口(interface)的拼写, namespace 等),而且编译器没有给我任何错误,所以我不知道为什么会发生此错误在运行时。

如果删除了IEditableObject约束,代码将在没有此异常的情况下运行,但是我的逻辑取决于该类是IEditableObject,因此这不是一个选择。

知道为什么会发生这种情况以及如何解决吗?

这些页面似乎相关,但我仍然不知道解决方案
  • https://connect.microsoft.com/VisualStudio/feedback/details/270717/reflection-emit-chokes-on-method-type-parameters
  • http://bytes.com/topic/c-sharp/answers/478595-reflection-generics-could-anyone-confirm-deny-bug

  • 这是.NET中的错误吗?有没有人找到解决方法?

    编辑:按要求声明
    public class DataEditor<T> : ViewModel, IDataEditor<T> where T :  IEditableObject
    
    public interface IDataEditor<T> : IDataEditor
        where T :  IEditableObject
    

    最佳答案

    由于相同的错误,我的项目无法构建。即使我没有使用任何此类通用类型的类。刚刚引用了它的程序集。

    当我删除它的accessor文件时,问题解决了。如果不需要accessor,将其删除可能是一个解决方案。

    这个答案可能对某人有用。

    关于c# - .NET告诉我TypeLoadException : violates the constraint of type parameter 'T' while my code clearly doesn't violate it,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7495797/

    10-12 02:20