7
novembre
2007
Extension method : C# différent de VB
novembre
2007
Dans l’excellent article de Adrian « Spotty » Bowles paru dans le msdn mag sur les extension methods en VB, l’auteur nous explique que ce code :
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim s As Integer = 1234
Console.WriteLine(s.Foo) '<- This will work
Dim T As Object
T = 1234
Console.WriteLine(T.Foo) '<- This will fail
End Sub
End Module
Module Extensions01
<Extension()> _
Function Foo(ByVal b As Object) As String
Return "Bar01"
End Function
End Module
Module Module1
Sub Main()
Dim s As Integer = 1234
Console.WriteLine(s.Foo) '<- This will work
Dim T As Object
T = 1234
Console.WriteLine(T.Foo) '<- This will fail
End Sub
End Module
Module Extensions01
<Extension()> _
Function Foo(ByVal b As Object) As String
Return "Bar01"
End Function
End Module
génère une exception à la compilation et c’est vrai !
Mais pas en C#.
Le code suivant marche en effet très bien :
class Program
{
static void Main(string[] args)
{
object o;
o = 10;
Console.WriteLine(o.Foo());
Console.ReadLine();
}
}
static class Ext
{
public static string Foo(this object o)
{
return "test";
}
}
{
static void Main(string[] args)
{
object o;
o = 10;
Console.WriteLine(o.Foo());
Console.ReadLine();
}
}
static class Ext
{
public static string Foo(this object o)
{
return "test";
}
}