C#Object构造函数 - 速记属性语法 [英] C# Object Constructor - shorthand property syntax
问题描述
几个月前,我阅读了一个技术,如果有参数传递匹配的局部变量,那么你可以使用一些短手法来设置它们。要避免此问题:
A few months ago i read about a technique so that if there paramaters 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;
}
任何想法?
推荐答案
你可能在想C#3.0中的新对象初始化语法。它看起来像这样:
You may be thinking about the new object initializer syntax in C# 3.0. It looks like this:
var foo = new Foo { Bar = 1, Fizz = "hello" };
这就是给我们一个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实例,我可以这样做:
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:
var foo2 = new Foo { foo1.Bar, foo1.Fizz };
这样就变得非常接近你的例子了。如果你的类有p1,p2和p3属性,并且你有同名的变量,你可以这样写:
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:
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.
这篇关于C#Object构造函数 - 速记属性语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!