コンバージョン・オペレーターを使ったクラスの初期化について
昔書いた「コンストラクタが勝手に代入してくれてうれしいんだけど、なんか不思議 - My Life as a Mock Quant」と同じものをC#でも考えてみましたというお話。
- Explicit版
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { class A { //Empty Class } class B { public B(A a) { a_ = a; } public static explicit operator B(A a) { return new B(a); } private A a_; } class C { public C(B b) { b_ = b; } private B b_; } static void Main(string[] args) { A a = new A(); C c = new C((B)a); //↓でも可能 //C c = new C(new B(a)); } } }
- Implicit版
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { class A { //Empty Class } class B { public B(A a) { a_ = a; } public static implicit operator B(A a) { return new B(a); } private A a_; } class C { public C(B b) { b_ = b; } private B b_; } static void Main(string[] args) { A a = new A(); C c = new C(a); } } }
- 参考リンク
Using Conversion Operators (C# Programming Guide) | Microsoft Docs