问题描述
我知道这应该是一个非常简单的问题,但我已经在这个概念上挣扎了一段时间.
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()
对于为什么?":
- 代码减少(总是一件好事)
需要来调用一个非默认的基础构造函数,例如:
- 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# 中进行构造函数链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!