如何在C#中进行构造函数链接 [英] How to do constructor chaining in C#
问题描述
我知道这应该是一个非常简单的问题,但是一段时间以来我一直在为这个概念而苦苦挣扎.
I know that this is supposedly a super simple question, but I've been struggling with the concept for some time now.
我的问题是,如何在C#中链接构造函数?
My question is, how do you chain constructors in C#?
我正在上第一门OOP课程,所以我只是在学习.我不了解构造函数链接的工作方式或实现方式,甚至不为什么比不进行链接的构造函数更好.
I'm in my first OOP class, so I'm just learning. I don't understand how constructor chaining works or how to implement it or even why it's better than just doing constructors without chaining.
我将对一些带有解释的示例表示赞赏.
I would appreciate some examples with an explanation.
那么如何将它们链接起来?
我知道有两个:
So how do how chain them?
I know with two it goes:
public SomeClass this: {0}
public SomeClass
{
someVariable = 0
}
但是您怎么用三个,四个等等呢?
But how do you do it with three, four and so on?
同样,我知道这是一个初学者的问题,但是我很难理解这一点,我也不知道为什么.
Again, I know this is a beginner question, but I'm struggling to understand this and I don't know why.
推荐答案
您使用标准语法(将this
用作方法)来选择重载,内部该类:
You use standard syntax (using this
like a method) to pick the overload, inside the class:
class Foo
{
private int id;
private string name;
public Foo() : this(0, "")
{
}
public Foo(int id, string name)
{
this.id = id;
this.name = name;
}
public Foo(int id) : this(id, "")
{
}
public Foo(string name) : this(0, name)
{
}
}
然后:
Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");
另请注意:
- 您可以使用
base(...)
链接到基本类型的构造函数
- 您可以在每个构造函数中添加额外的代码
- 默认值(如果您未指定任何内容)为
base()
- you can chain to constructors on the base-type using
base(...)
- you can put extra code into each constructor
- the default (if you don't specify anything) is
base()
对于为什么?":
- 减少代码(总是一件好事)
-
必要的来调用非默认的基本构造函数,例如:
- code reduction (always a good thing)
necessary to call a non-default base-constructor, for example:
SomeBaseType(int id) : base(id) {...}
请注意,尽管(无需编写任何内容),您也可以类似的方式使用对象初始化程序:
Note that you can also use object initializers in a similar way, though (without needing to write anything):
SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
z = new SomeType { DoB = DateTime.Today };
这篇关于如何在C#中进行构造函数链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!