# VBタグ作るのがめんどいので雑記タグで。
ネタ元:Code++ - VB でマルチプルディスパッチ
VB Tips and Trips: Multiple Dispatch
Option Strict Off
Class Base
End Class
Class Derived : Inherits Base
End Class
Module Module1
Sub Main()
Dim obj
obj = New Base
Foo(obj)
obj = New Derived
Foo(obj)
End Sub
Sub Foo(ByVal a As Base)
Console.WriteLine("Base")
End Sub
Sub Foo(ByVal b As Derived)
Console.WriteLine("Derived")
End Sub
End Module
Base
Derived
実行時型情報でルックアップしてるw
C# 4.0 でも dynamic 使えばできるとかできないとか。
こんな感じ?
using System;
namespace Program
{
class Base {}
class Derived : Base {}
class Program
{
static void Main(string[] args)
{
dynamic obj;
obj = new Base();
Foo(obj);
obj = new Derived()
Foo(obj);
}
static void Foo(Base a)
{
Console.WriteLine("a");
}
static void Foo(Derived b)
{
Console.WriteLine("b");
}
}
}
Visual Studio 2010 CTP では Foo(obj); がコンパイル通らなかった
Foo は dynamic 型を受け取らないといけないのかな
C# Feature Focus: Dynamically Typed Objects, Duck Typing, and Multiple Dispatch
追記:id:ufcppさんからいただいた情報で、C# 4.0でも多重ディスパッチできました
using System;
namespace CsConsole
{
class Base { }
class Derived : Base { }
class Program
{
static void Main(string[] args)
{
dynamic instance = new Program();
dynamic obj;
obj = new Base();
instance.Foo(obj);
obj = new Derived();
instance.Foo(obj);
}
public void Foo(Base a)
{
Console.WriteLine("a");
}
public void Foo(Derived b)
{
Console.WriteLine("b");
}
}
}