特定の機能を持つ構造型を定義する方法はありません。C# にダック タイピングのサポートを追加するライブラリがあり、ここで見つけることができます。
これは Duck Typing プロジェクトの例です。ダックタイピングは実行時に発生し、失敗する可能性があることに注意してください。また、このライブラリがダック型の型のプロキシを生成することも理解しています。これは、Scala で享受されているエレガントなコンパイル時のサポートとはかけ離れています。これは、この世代の C# で得られるものと同じくらい優れている可能性が高いです。
public interface ICanAdd
{
int Add(int x, int y);
}
// Note that MyAdder does NOT implement ICanAdd,
// but it does define an Add method like the one in ICanAdd:
public class MyAdder
{
public int Add(int x, int y)
{
return x + y;
}
}
public class Program
{
void Main()
{
MyAdder myAdder = new MyAdder();
// Even though ICanAdd is not implemented by MyAdder,
// we can duck cast it because it implements all the members:
ICanAdd adder = DuckTyping.Cast<ICanAdd>(myAdder);
// Now we can call adder as you would any ICanAdd object.
// Transparently, this call is being forwarded to myAdder.
int sum = adder.Add(2, 2);
}
}
これは、古き良き退屈なインターフェースを使用して同じことを達成する C# の方法です。
interface IPressable {
void Press();
}
class Foo {
void Bar(IPressable pressable) {
pressable.Press();
}
}
class Thingy : IPressable, IPushable, etc {
public void Press() {
}
}
static class Program {
public static void Main() {
pressable = new Thingy();
new Foo().Bar(pressable);
}
}