C#构造函数默认值提供时机及相关构造逻辑咨询
C# 转 TypeScript 疑问解答
背景
正在将以下C#代码移植到TypeScript(刚接触C#):
namespace R3.Geometry { public class Tile { public Tile() { Isometry = new Isometry(); EdgeIncidences = new List<Tile>(); VertexIndicences = new List<Tile>(); } public Tile( Polygon boundary, Polygon drawn, Geometry geometry ) : this() { Boundary = boundary; Drawn = drawn; Geometry = geometry; VertexCircle = boundary.CircumCircle; } public Isometry Isometry { get; set; } public Polygon Boundary { get; set; } public Polygon Drawn { get; set; } public CircleNE VertexCircle { get; set; } public Geometry Geometry { get; set; } public Tile Clone() { Tile newTile = new Tile(); newTile.Boundary = Boundary.Clone(); newTile.Drawn = Drawn.Clone(); newTile.VertexCircle = VertexCircle.Clone(); newTile.Geometry = Geometry; return newTile; } // ...rest... } }
已了解get; set属性无默认值,第二个构造函数的: this()表示先调用无参构造函数,针对以下疑问解答:
疑问1:若仅调用无参构造函数创建Tile实例,Boundary、Drawn等属性未初始化,此时调用Clone方法中的Boundary.Clone()是否会报错?
- 会报错。C#中引用类型的默认值是
null,无参构造没有给Boundary、Drawn等属性赋值,所以这些属性的值都是null。调用null对象的Clone()方法会直接抛出NullReferenceException。
疑问2:调用无参构造函数时,是否会通过默认参数调用其他构造函数?Boundary等属性是否会被自动初始化?
- 不会调用其他构造函数,无参构造是独立执行的。
Boundary这类引用类型属性不会自动初始化,默认值为null;只有值类型(比如int、bool)才会自动设置为对应默认值。只有在构造函数中显式赋值,这些引用类型属性才会被初始化。
疑问3:如下TilingConfig结构体的两个构造函数均使用: this(),其含义是什么?
public struct TilingConfig { public TilingConfig( int p, int q, int maxTiles ) : this() { SetupConfig( p, q, maxTiles ); } public TilingConfig( int p, int q ) : this() { if( Geometry2D.GetGeometry( p, q ) != Geometry.Spherical ) throw new System.ArgumentException(); SetupConfig( p, q, PlatonicSolids.NumFacets( p, q ) ); } // no more constructors. }
- 对于C#结构体(
struct),自定义构造函数后,默认的无参构造不会自动生效。: this()的作用是强制触发结构体的默认初始化逻辑,把所有字段设置为对应类型的默认值(引用类型为null,值类型如int为0、bool为false等)。这么做是为了避免结构体存在未初始化的字段,导致编译或运行时错误。
疑问4:构造函数参数中的复杂对象(如Polygon boundary)是否会被默认初始化?
- 不会。构造函数的参数值完全由调用者传入决定,C#不会自动为参数创建实例。如果调用构造时传入
null,那boundary参数就是null;必须由调用者传入一个有效的Polygon实例,参数才会指向该对象。
内容的提问来源于stack exchange,提问作者Lance Pollard
相关产品推荐
相关产品推荐

