Utilizzare gli Extension Methods nel framework 2.0
Scritto da
Simone Di Stasio il
mercoledì 9 novembre 2011
•
Linguaggio:
• Livello: 200
Per poter abilitare l'utilizzo degli extension
methods con il framework 2.0, è sufficiente dichiarare
la seguente classe:
C#
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
public sealed class ExtensionAttribute : Attribute
{
}
}
VB.NET
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Method Or AttributeTargets.Class Or AttributeTargets.Assembly)> _
Public Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
In questo modo possiamo creare gli extension
methods come se ci si trovasse nel framework
3.5.
Ad esempio:
C#
public static class StringExtension
{
public static bool LengthIsGreathenThan(this string source, int requiredLength)
{
return source.Length > requiredLength;
}
}
VB.NET
Public Module StringExtension
<Extension()> _
Public Function LengthIsGreathenThan(ByVal source As String, ByVal requiredLength As Integer) As Boolean
Return source.Length > requiredLength
End Function
End Module
Questo può avvenire perchè il CLR del Framework 3.5 è lo stesso del
Framework 2.0 e gli Extensions Methods sono solo
syntactic sugar (ovviamente non sono presenti gli
extension methods introdotti
specificatamente nella versione 3.5 come quelli a supporto di
LINQ).
Per gli utilizzatori di Visual Basic attenzione al namespace di
default che Visual Studio mette negli assembly. L'attributo
ExtensionAttribute deve trovarsi esattamente nel namespace di
sistema System.Runtime.CompilerServices.
Tags: extension methods