简体   繁体   English

C#Object Constructor - 简写属性语法

[英]C# Object Constructor - shorthand property syntax

A few months ago I read about a technique so that if there parameters you passed in matched the local variables then you could use some short hand syntax to set them. 几个月前,我读到了一种技术,如果传入的参数与局部变量匹配,那么你可以使用一些简短的语法来设置它们。 To avoid this: 为了避免这种情况

public string Method(p1, p2, p3)
{
    this.p1 = p1;
    this.p2 = p2;
    this.p3 = p3;
}

Any ideas? 有任何想法吗?

You may be thinking about the new object initializer syntax in C# 3.0. 您可能正在考虑C#3.0中的新对象初始化程序语法。 It looks like this: 它看起来像这样:

var foo = new Foo { Bar = 1, Fizz = "hello" };

So that's giving us a new instance of Foo, with the "Bar" property initialized to 1 and the "Fizz" property to "hello". 所以这给了我们一个新的Foo实例,“Bar”属性初始化为1,“Fizz”属性为“hello”。

The trick with this syntax is that if you leave out the "=" and supply an identifier, it will assume that you're assigning to a property of the same name. 使用这种语法的技巧是,如果省略“=”并提供标识符,它将假定您正在分配给同名的属性。 So, for example, if I already had a Foo instance, I could do this: 所以,例如,如果我已经有一个Foo实例,我可以这样做:

var foo2 = new Foo { foo1.Bar, foo1.Fizz };

This, then, is getting pretty close to your example. 然后,这与你的例子非常接近。 If your class has p1, p2 and p3 properties, and you have variables with the same name, you could write: 如果您的类具有p1,p2和p3属性,并且您具有相同名称的变量,则可以编写:

var foo = new Foo { p1, p2, p3 };

Note that this is for constructing instances only - not for passing parameters into methods as your example shows - so it may not be what you're thinking of. 请注意,这仅用于构造实例 - 不是用于将参数传递给方法,如您的示例所示 - 因此它可能不是您想要的。

You might be thinking of the "object initializer" in C#, where you can construct an object by setting the properties of the class, rather than using a parameterized constructor. 您可能正在考虑C#中的“对象初始化程序”,您可以通过设置类的属性来构造对象,而不是使用参数化构造函数。

I'm not sure it can be used in the example you have since your "this" has already been constructed. 我不确定它是否可以用在你已经构建的“this”中的示例中。

There's an even easier method of doing this in C# 7 - Expression bodied constructors. 在C#7中有一个更简单的方法 - 表达体的构造函数。

Using your example above - your constructor can be simplified to one line of code. 使用上面的示例 - 您的构造函数可以简化为一行代码。 I've included the class fields for completeness, I presume they would be on your class anyway. 为了完整性,我已经将类字段包含在内,我认为无论如何它们都会在你的课程中。

private string _p1;
private int _p2;
private bool _p3;  

public Method(string p1, int p2, bool p3) => (_p1, _p2, _p3) = (p1, p2, p3);

See the following link for more info :- 有关详细信息,请参阅以下链接: -

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

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

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