简体   繁体   中英

C# Constructor default arguments

Usually a Constructor in C# is repeating a lot of assignements to symbols that already exist.

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 . 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. 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). And you use optional parameters (as the seeing of z in the last foo constructor shows).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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