【发布时间】:2013-07-07 18:25:25
【问题描述】:
我正在阅读 Beginning Visual C# 2012。
考虑:
using System;
using System.Collections.Generic;
using System.Text;
namespace Ch10Ex01
{
class MyClass
{
public readonly string Name;
private int intVal;
public int Val
{
get { return intVal; }
set
{
if (0 <= value && value <= 10)
intVal = value;
else
throw (new ArgumentOutOfRangeException("Val", value,
"Val must be assigned a value between 0 and 10."));
}
}
public override string ToString()
{
return "Name: " + Name + "\nVal: " + Val;
}
private MyClass() : this("Default Name")
{
}
public MyClass(string newName)
{
Name = newName;
intVal = 0;
}
}
}
书中的解释:请注意,我已使用 this(“默认名称”)来确保 Name 在此构造函数被调用时获得一个值,如果该类用于派生一个新类,则这是可能的。这是必要的,因为不为 Name 字段分配值可能会导致以后出现错误。
让我感到困惑的是:它是“私有”的,如何在派生类中使用它?这(“默认名称”)是什么意思?对象如何获取“默认名称”作为其名称?
【问题讨论】:
-
"查看 cmets"。什么cmets?
标签: c# constructor private