.NET tells me TypeLoadException: violates the constraint of type parameter 'T' while my code clearly doesn't violate it
I am trying to initialize an object of DataEditor<Student>
, where my DataEditor<T>
class implements interface IDataEditor<T> where T : IEditableO开发者_JS百科bject
.
DataEditor<Student> editor = GetEditorFor(student);
During runtime, I got a TypeLoadException saying: GenericArguments[0], 'Namespace.Data.Student', on 'Namespace.IDataEditor`1[T]' violates the constraint of type parameter 'T'. The exception happens on the line above, before it even goes inside the GetEditorFor method.
The only constraint on T is IEditableObject
, and my Student
class clearly implements it (I double checked the interface spelling, namespace, etc.), and also the compiler doesn't give me any error, so I have no idea why this error happens on runtime.
If I remove the IEditableObject
constraint, the code runs without this exception, but my logic depends on the class being an IEditableObject
, so it is not an option.
Any idea why this happens and how to fix it?
These pages seems to be related, but I still don't know the solution
- 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
Is this a bug in .NET? Has anyone found a workaround?
Edit: declaration as requested
public class DataEditor<T> : ViewModel, IDataEditor<T> where T : IEditableObject
public interface IDataEditor<T> : IDataEditor
where T : IEditableObject
My project could not build because of the same error. Even if I did not use any of this generic typed class. Its assembly was just referenced.
When I delete the accessor
file of it, problem solved. If you do not need accessor
, deleting it may be a solution.
This answer may useful for someone.
What happens is that Student
does not implement IEditableObject
, the GetEditorFor
method probably has a where
clause where T
must be IEditableObject
, and the T
that you are passing is Student
and not IDataEditor
.
That's why you're getting this error, you're violating the method signature sending a T
that is not IEditableObject.
You should either implement IEditableObject
into the Student
class, or remove the where T : IEditableObject
clause.
精彩评论