Up casting - c#

前端 未结 6 1016
星月不相逢
星月不相逢 2021-01-17 15:57
public class a{
  public string x1 {get;set;}
  public string x2 {get;set;}
  public string x3 {get;set;}
}

public class b:a{
}

Obviously v

相关标签:
6条回答
  • 2021-01-17 16:31

    Actually, your idea of creating a new instance of b and copying a's field values to it seems like an interesting approach. using reflection to achieve this should fit the bill nicely.

    Something like: iterate through all of a's fields, get their values as stored in a and store them in the same field in b.

    Still, this is not "downcasting" -- since it means a completely different object is created -- as opposed to reinterpreting the meaning of an existing object.

    0 讨论(0)
  • 2021-01-17 16:34

    This type of cast is wrong, because you can't cast parents to their children.
    Type of a doesn't know about metainformation of type b. So you need provide the explicit cast operator to do such things, but in this case you must remove inheritance.
    Other option is to define some interface, such as in other questions.

    More information:
    http://msdn.microsoft.com/en-us/library/ms173105.aspx
    http://msdn.microsoft.com/en-us/library/85w54y0a.aspx

    0 讨论(0)
  • 2021-01-17 16:37

    This is something that has always bothered me as well. I worked out a solution to it by creating my own Up-Casting utility.

    You can read my article here on how to do it -- it's pretty simple actually.

    http://sympletech.com/c-up-casting-utility/

    0 讨论(0)
  • 2021-01-17 16:40

    Not possible. Even if you think you have it, the compiler will complain.

    This usually indicates a design or logical error.

    0 讨论(0)
  • 2021-01-17 16:44

    As everyone's saying, it's not possible. Implicit casting is one solution, but I prefer to create a constructor on b that takes an instance of type a...

    That way you can either: hold a reference to that a internally and delegate to it calls b inherits from a, or just simply copy the values out of the type a.

    0 讨论(0)
  • 2021-01-17 16:48

    You can't make that cast.

    You can, and I guess you should, use an interface.

    public interface ia
    {
        string x1 { get; set; }
        string x2 { get; set; }
        string x3 { get; set; }
    }
    public class a : ia
    {
        public string x1 { get; set; }
        public string x2 { get; set; }
        public string x3 { get; set; }
    }
    
    public class b : a, ia
    {
    }
    

    Then you can

    ia foo = new a();
    
    0 讨论(0)
提交回复
热议问题