29
mars
2007
Le compilateur VB ignore-t-il que tout est Object ?
mars
2007
Désolé Florent, c’est encore du VB
J’ai eu une énorme surprise aujourd’hui.
J’avais une propriété de type IEnumerable et je voulais faire un GetType sur Value.
En C#, cela se fait très bien :
class Program
{
static void Main(string[] args)
{
List<string> l = new List<string>();
Test.Toto = l;
Console.ReadLine();
}
}
public class Test
{
public static IEnumerable Toto
{
get { return null; }
set { Console.WriteLine(value.GetType().ToString()); }
}
}
{
static void Main(string[] args)
{
List<string> l = new List<string>();
Test.Toto = l;
Console.ReadLine();
}
}
public class Test
{
public static IEnumerable Toto
{
get { return null; }
set { Console.WriteLine(value.GetType().ToString()); }
}
}
En VB, j’aurais écris ceci :
Sub Main()
Dim l As New List(Of String)
Test.Toto = l
Console.ReadLine()
End Sub
Public Class Test
Public Shared Property Toto() As IEnumerable
Get
Return Nothing
End Get
Set(ByVal value As IEnumerable)
Console.WriteLine(value.GetType().ToString())
End Set
End Property
End Class
Dim l As New List(Of String)
Test.Toto = l
Console.ReadLine()
End Sub
Public Class Test
Public Shared Property Toto() As IEnumerable
Get
Return Nothing
End Get
Set(ByVal value As IEnumerable)
Console.WriteLine(value.GetType().ToString())
End Set
End Property
End Class
Et bien non ! En effet, le compilateur me dit que « ‘GetType’ n’est pas un membre de ‘System.Collections.IEnumerable' ».
En fait, c’est le cas pour n’importe quelle variable typée en interface.
Je suis donc obligé de caster value en Object :
Console.WriteLine(DirectCast(value, Object).GetType().ToString())