开发者

C# set inherited class equal to base class

开发者 https://www.devze.com 2023-02-15 11:29 出处:网络
if I have a parent class: public class ParentClass { public string ParentStr = string.empty; } and a child class:

if I have a parent class:

public class ParentClass
{
  public string ParentStr = string.empty;
}

and a child class:

public class ChildClass : ParentClass
{
  public string ChildStr = string.empty;
}

Say later in my code I have an instance of ParentClass

ParentClass parentClass = New ParentClass() { ParentStr = "something" } 

Is it possible to create an instance of the ChildClass from the ParentClass? Something to the effect of:

ChildClass childClass 开发者_如何转开发= (ChildClass)parentClass


I imagine you could provide an implicit or explicit operator to do this, though it seems pretty weird.

Subclassing defines an is-a relationship, but the subclass is-a superclass, not the other way around. Without knowing what your classes are, I think you've got design issues outside of this.


Think of it in English terms: if your parent class is an Animal and the child class is a Dog, can you say, without any doubt, that an Animal is a Dog?

Answering a question with another question is not great, so the real answer is: no, you cannot cast an instance of a base class into a child class.

However, if you stored an instance of the child class in a variable of the type of the base class, you are allowed to cast it back to the child class. The following is valid:

ParentClass p = new ChildClass();
ChildClass  c = (ChildClass)p;


No. ChildClass is a different type, and you can't cast an actual runtime instance of the ParentClass to the ChildClass.


What would be the purpose? If such a construct existed, then the new ChildClass would, I suppose, just have the default values for any properties that extended ParentClass. Just create a ChildClass object to begin with.

You can always use a base class type container for inherited classes. You should not be trying to recreate an instance of an object to a derived type, instead, you should be creating an instance of the derived type, and using the base type container if you want to be able to interchange the objects:

ParentClass parentClass = new *ChildClass*() { ParentStr = "something" } 
ChildClass childClass = (ChildClass)parentClass

I am not recommending these naming conventions :)

0

精彩评论

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

关注公众号