If you get an error like shown below; this is probably due to the downgrade of a project from .NET 3.5 or higher to .NET 2.0
Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?
Extension methods are a new feature in .NET 3.5 (C#3/VB9) that let you appear to "spot weld" new methods on to existing classes.
If you think that the "string" object needs a new method, you can just add it and call it on instance variables.
But how do we accomplish this in .NET 2.0?
VB.NET
' you need this once (only), and it must be in this namespaceNamespace System.Runtime.CompilerServices<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.[Class] Or AttributeTargets.Method)> _
Public NotInheritable Class ExtensionAttribute
Inherits AttributeEnd Class
End Namespace
' you can have as many of these as you like, in any namespacesPublic NotInheritable Class MyExtensionMethods
Private Sub New()
End Sub
<System.Runtime.CompilerServices.Extension> _
Public Shared Function MeasureDisplayStringWidth(graphics As Graphics, text As String) As Integer
' ... End Function
End Class
C#
// you need this once (only), and it must be in this namespacenamespace System.Runtime.CompilerServices{[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
| AttributeTargets.Method)]
public sealed class ExtensionAttribute : Attribute {}
}
// you can have as many of these as you like, in any namespacespublic static class MyExtensionMethods {
public static int MeasureDisplayStringWidth (
this Graphics graphics, string text )
{ /* ... */}
}
No comments:
Post a Comment