Cannot implicitly convert type 'customtype' to 'othercustomtype'

前端 未结 5 864
鱼传尺愫
鱼传尺愫 2020-12-06 17:25

I am new to C#. I have a Persons class and a User class which inherits from the Persons class. I my console I input a users in an array. Then I can add a note to a user that

5条回答
  •  余生分开走
    2020-12-06 18:19

    You need to implement explicit or implicit operator:

    class ClassA
    {
        public string Property1 { get; set; }
    
        public static explicit operator ClassB(ClassA classA)
        {
            return new ClassB() { Property2 = classA.Property1 };
        }
    }
    
    class ClassB
    {
        public string Property2 { get; set; }
    }
    
    var a = new ClassA() {Property1 = "test"};
    ClassB b = (ClassB)a;
    Console.WriteLine(b.Property2); // output is "test"
    

提交回复
热议问题