When converting a project (in which a template method of 开发者_高级运维IComparable was used a few times) from VS 2005 to VS 2008 I've got some errors:
Error 12 Type argument 'Object' does not inherit from or implement
the constraint type 'System.IComparable'.
Is this an actual fact that System.Object no longer implements that interface, or something went wrong during the convertion? Can I fix this somehow?
The problem is with the following method:
Public Function ValueIn(Of T As IComparable)(ByVal pValue As T, ByVal ParamArray pArgs() As T) As Boolean
For Each MyArg As T In pArgs
If pValue.CompareTo(MyArg) = 0 Then
Return True
End If
Next
Return False
End Function
and even something simple like:
Dim a as Object = 1
ValueIn(a,1,2)
causes the error mentioned above. It worked perfectly in VS 2005, so what can be the problem now?
EDIT: I have just tried your code in both VS 2005 and 2008.
You have Option Strict Off
configured in your project or source code file. Your code never worked in the first place, and if you set Option Strict On
in VS 2005, you will see the real cause of the error, which is "Type argument inference failed for type parameter 'T'". I recommend that Option Strict On
be used in all VB.NET code.
You see a different error in VS 2008 because it is using a newer version of the language, with very different overloading and type inference rules. In VB.NET 2008, the compiler cannot resolve the method call regardless of whether Option Strict
is on or off.
The System.Object
type does not and has never implemented any interface.
The setting of Option Infer
in VS 2008 is not relevant to your code because it does not make use of any inferred types.
The simplest way to fix the error in both IDEs is to change the calling code thus:
Dim a As Integer = 1
ValueIn(a, 1, 2)
If you run the debug the code in Visual Studio 2005 you will see that the a from
Dim a as Object = 1
is an Integer but if you use 2008 it will state that it's an Object.
Integer have the interface IComparable impelemented but not Object. So what to do? Answer: Got the the projects properties (right click the project name and select properties), Go in under 'Compile' and there you now have except the explicit, strict and compare, that you had in 2005, an new field named Infer. Change that value.
And now we cross our fingers that this will work.
System.Object was IComparable? How did that work? IEquatable I can understand but IComparable doesn't make sense.
Can you expand on "template method"? Maybe that's a clue.
I'm 99% sure this is caused by a change in .Net 3.5 with the template class IComparable. I've seen a couple of earlier .NET examples that work fine but generate errors in 3.5.
精彩评论