C# 对象构造函数 - 简写属性语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/506635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Object Constructor - shorthand property syntax
提问by Schotime
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?
有任何想法吗?
采纳答案by Matt Hamilton
You may be thinking about the new object initializer syntax in C# 3.0. It looks like this:
您可能正在考虑 C# 3.0 中的新对象初始值设定项语法。它看起来像这样:
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.
请注意,这仅用于构造实例 - 不是用于将参数传递到您的示例所示的方法中 - 所以它可能不是您所想的。
回答by Andy White
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”已经被构建了。
回答by grimdog_john
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 :-
有关更多信息,请参阅以下链接:-