cast class into another class or convert class to another

前端 未结 9 652
逝去的感伤
逝去的感伤 2020-11-28 22:29

my question is shown in this code

I have class like that

public class  maincs
{
  public int a;
  public int b;
  public int c;
  public int d; 
}
         


        
9条回答
  •  无人及你
    2020-11-28 23:12

    You can provide an explicit overload for the cast operator:

    public static explicit operator maincs(sub1 val)
    {
        var ret = new maincs() { a = val.a, b = val.b, c = val.c };
        return ret;
    }
    

    Another option would be to use an interface that has the a, b, and c properties and implement the interface on both of the classes. Then just have the parameter type to methoda be the interface instead of the class.

提交回复
热议问题