开发者

Up casting - c#

开发者 https://www.devze.com 2023-03-13 07:49 出处:网络
publi开发者_如何转开发c class a{ public string x1 {get;set;} public string x2 {get;set;} public string x3 {get;set;}
publi开发者_如何转开发c class a{
  public string x1 {get;set;}
  public string x2 {get;set;}
  public string x3 {get;set;}
}

public class b:a{
}

Obviously var foo = (b)new a(); will throw a casting error at runtime.

The only other way I can think to assign all the properties of an already instantiated and populated a is to manually copy each one over into a fresh instance of b.

Is this correct?


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


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

This usually indicates a design or logical error.


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/


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();


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消