简体   繁体   English

C# 构造函数默认参数

[英]C# Constructor default arguments

Usually a Constructor in C# is repeating a lot of assignements to symbols that already exist.通常 C# 中的构造函数会重复对已经存在的符号进行大量赋值。

As an example:举个例子:

 class P{
    int x;
    int y;
    int z;
    P(int x,int y,int z,...)
     {
       this.x=x;
       this.y=y;
      this.z=z;
      /...
    }
 }

Is there a way to default assign constructor inputs to fields of the same name.有没有办法将构造函数输入默认分配给同名的字段。 It makes no sense to reimplement this one-one map for every class.为每个班级重新实现这个一对一的地图是没有意义的。

Currently it's not possible.目前是不可能的。

But there is a feature in C# backlog called Records .但是 C# backlog 中有一个功能叫做Records Though I'm not sure if we'll see it in C# 7. Record types allow one-line definition of classes with set of properties which automatically will be assigned with constructor arguments.虽然我不确定我们是否会在 C# 7 中看到它。记录类型允许单行定义具有一组属性的类,这些属性将自动分配给构造函数参数。 Eg例如

public class Point(int X, int Y);

Which is same as这与

public class Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
       X = x;
       Y = y;
    }

    // plus Equals, GetHashCode, With
}

Not in the way you are thinking (if I understand you correctly).不是你想的方式(如果我理解正确的话)。 The names of the parameters to the constructor and the names of the fields/properties are really just convenient labels for humans.构造函数的参数名称和字段/属性的名称实际上只是人类的方便标签。 A class should be independent and encapsulate it's state.一个类应该是独立的并封装它的状态。 Even allowing an compiler option to make external (passed in) names equate the internal ones confuses that concept.即使允许编译器选项使外部(传入)名称等同于内部名称也会混淆该概念。

You can do things like this:你可以做这样的事情:

    public class foo {
    public int X { get; set; }
    public string Y { get { return X.ToString(); } }
    public double Z { get; private set; }
    private foo(int x) { X = x; }
    public foo(int x, string y, double z = 1.0): this(x) {
        Z = z;
        }
    }

Where a public constructor uses a private constructor (or other public constructor) to do some of the work (as the last foo constructor does).公共构造函数使用私有构造函数(或其他公共构造函数)来完成一些工作(就像最后一个 foo 构造函数所做的那样)。 And you use optional parameters (as the seeing of z in the last foo constructor shows).并且您使用可选参数(如在最后一个 foo 构造函数中看到的 z 所示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM