æé»ã®åå¤æ
implicit operatorã使ã£ã¦ç¶æ¿ã®çä¼¼äºããã¦ã¿ã¦æã£ãã®ã§ãããã¤ã³ã¿ãã§ã¼ã¹ç¶æ¿æã«implicit operatorãæå®ããã¦ããããã¤ã³ã¿ãã§ã¼ã¹ã¯å®è£ æ¸ã¿ã¨ãã¦ãããã便å©ãªæ°ããã¾ãã
using System; public class Person { string name; int age; public Person(string name, int age) { this.name = name; this.age = age; } public string Name { get { return name; } } public int Age { get { return age; } } } public class Programmer { Person person; string langage; public Programmer(Person person, string langage) { this.person = person; this.langage = langage; } public string Langage { get { return langage; } } public static implicit operator Person(Programmer src) { return src.person; } } public class Manager { Person person; string dept; public Manager(Person person, string dept) { this.person = person; this.dept = dept; } public string Dept { get { return dept; } } public static implicit operator Person(Manager src) { return src.person; } } public class ProgramManager : Person { Programmer programmer; Manager manager; public ProgramManager(string name, int age, string dept, string langage) : base(name, age) { programmer = new Programmer(this, langage); manager = new Manager(this, dept); } public static implicit operator Programmer(ProgramManager src) { return src.programmer; } public static implicit operator Manager(ProgramManager src) { return src.manager; } } class Program { static string PrintBase(Person person) { return String.Format("name = {0}, age = {1}", person.Name, person.Age); } static void PrintProgrammer(Programmer programmer) { Console.WriteLine("{0}, lang = {1}", PrintBase(programmer), programmer.Langage); } static void PrintManager(Manager manager) { Console.WriteLine("{0}, dept = {1}", PrintBase(manager), manager.Dept); } static void Main(string[] args) { ProgramManager pm = new ProgramManager("taro", 20, "Product", "C#"); PrintProgrammer(pm); PrintManager(pm); } } /* name = taro, age = 20, lang = C# name = taro, age = 20, dept = Product */
ä¸è¨ãã
public class ProgramManager : Person, IProgrammer, IManager { Programmer programmer; Manager manager; public ProgramManager(string name, int age, string dept, string langage) : base(name, age) { programmer = new Programmer(this, langage); manager = new Manager(this, dept); } public static implicit operator IProgrammer(ProgramManager src) { // src.programmerã¯IProgrammerãå®è£ ãã¦ãã return src.programmer; } public static implicit operator IManager(ProgramManager src) { // src.managerã¯IManagerãå®è£ ãã¦ãã return src.manager; } }
ãããªæãã§æ¸ããã¦ããããè¯ãã£ãã®ã«ã