派生类使用基类初始化 [英] Derived class initialize with base class
问题描述
大家好,
我有一个非常有趣的问题。使用基类初始化派生类。
我的意思是有两个名为DerivedClass和BaseClass的类。 DerivedClass由BaseClass派生。我想做类似的事情
Hi people,
I have very interesting question. initialization of derived class with its base class.
I mean there are two class named DerivedClass and BaseClass. DerivedClass derived by BaseClass. I want to do something like that
class DerivedClass
{
public DerivedClass(BaseClass bc)
{
base = bs;
}
}
可能吗?
is that possible?
推荐答案
不,我觉得你很困惑。
No, I think you are confused.
class DerivedClass
{
public DerivedClass(BaseClass bc)
{
base = bs;
}
}
您的DerivedClass与BaseClass无关 - 除了通过对象,他们两者都来源于。 (忽略拼写错误bs/bc)
您更可能想说:
Your "DerivedClass" is not related to "BaseClass" - except via Object which they both derive from. (Ignoring the typo "bs" / "bc")
You more likely want to say:
class DerivedClass : BaseClass
{
public DerivedClass(BaseClass bc)
{
base = bc;
}
}
哪个派生自基地。但在这种情况下,您不需要从Base Class实例创建DerivedClass实例,因为Derived类是Baseclass的类型 - 它已经包含基类的所有字段,属性,事件和方法。 />
你所拥有的基本上是一个复制构造函数(你可以做),但除非你的系统设计的其余部分相当奇怪,否则它应该是无关紧要的。
更好的编码方式是:
Which does derive from the base. But in that case, you don't need to create a DerivedClass instance from a Base Class instance, because Derived class is a type-of Baseclass - it already contains all the fields, properties, event and methods of the base class.
What you have there is basically a copy constructor (which you can do) but which should be irrelevant unless the rest of your system design is rather odd.
A better way to code it would be:
class DerivedClass : BaseClass
{
public DerivedClass(BaseClass bc) : base (bc)
{
}
}
但即便如此,这也是一个奇怪的想法。
什么是你想要这样做你认为你需要这个吗?
But even then it's an odd idea.
What are you trying to do that you think you need this?
我认为这更相关:
类DerivedClass:BaseClass
{
string som eOtherInfo;
public DerivedClass(BaseClass bc)
{
base = bc;
}
}
即初始化字段的Derived类字段的BaseClass-ness。
我不确定这是否可以在C#中完成。在C ++中,我想我可以做*(基于类)这个= bc;
在C#中,我想你可以做到:
I think this is more relevant:
class DerivedClass : BaseClass
{
string someOtherInfo;
public DerivedClass(BaseClass bc)
{
base = bc;
}
}
I.e. initialize the BaseClass-ness of the Derived class field for field.
I am not sure if this can be done in C#. In C++ I think I could have done *(BasedClass)this = bc;
In C#, I think you might be able to do:
class DerivedClass : BaseClass
{
string someOtherInfo;
public DerivedClass(BaseClass bc) : base(bc)
{
}
}
但是,这需要在BaseClass中有这样的构造函数。
However, that requires that there is such a constructor in BaseClass.
这篇关于派生类使用基类初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!