我有一个派生类,它派生自基类
public class DerivedClass : BaseClass
{
public DerivedClass () {}
public DerivedClass ( BaseClass bc )
{
// The following line is invalid, but I want to achieve something like this
this = bc;
// Error: (this) Cannot assign <This> because this is read only
// Error2: (bc) Cannot implicitly convert Type `BaseClass` to `DerivedClass`
}
}
public class BaseClass
{
public string TestName { get; set; }
public uint TestNumber { get; set; }
public BaseClass () { }
}
然后从Main
方法
static void Main ( string[] args )
{
BaseClass bc = new BaseClass ();
bc.TestName = "dummy test";
bc.TestNumber = 007;
DerivedClass dc = new DerivedClass ( bc );
}
现在我的问题是,
this = bc;
)? 谢谢!
答案 0 :(得分:1)
this
是只读别名 - 记住将来
你可以这样做
public class DerivedClass : BaseClass
{
public DerivedClass () {}
public DerivedClass ( BaseClass bc )
{
TestName=bc.TestName;
TestNumber=bc.TestNumber;
}
}
这是一种正确的编码实践,如果不是为什么? 取决于你尝试实现的目标
答案 1 :(得分:1)
你不能这样做,你不能在引用当前实例的构造函数中使用this
,因为你刚才要构造对象。我会提供合适的构造函数:
public class DerivedClass : BaseClass
{
public DerivedClass() { }
public DerivedClass(string TestName, uint TestNumber)
{
base.TestName = TestName;
base.TestNumber = TestNumber;
}
public DerivedClass(BaseClass bc) : this(bc.TestName, bc.TestNumber) { }
}
因此,如果您在示例中没有使用BaseClass
变量,则根本不需要它。为初始化子类对象创建一个基础对象毫无意义。
答案 2 :(得分:1)
这是一种不好的做法。
这意味着你的基类已经代表派生类的任何内容。
我推荐作文:
public class TestData
{
public string TestName { get; set; }
public uint TestNumber { get; set; }
}
public class BaseClass
{
protected TestData data;
public BaseClass(TestData data)
{
this.data = data;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(TestData data)
: base(data)
{
}
}