Info myPath = new Info()
{
path = oFile.FileName
};
...
class Info
{
public string path;
public string Path
{
get { return path; }
set { path = value; }
}
}
以上是某些程序的C#代码,它可以正常工作。但我不太了解它。第一个问题是为什么path = oFile.FileName
不是path = oFile.FileName;
?为什么分号可以删除?
第二个问题是为什么我不能这样写:myPath.path = oFile.FileName
? Visual Studio 2012会给出错误消息。
有人可以帮忙吗?谢谢!
答案 0 :(得分:3)
您可以通过多种方式在C#中初始化对象。 在这里你可以做你所写的,这将是相当于:
Info myPath = new Info();
myPath.Path = oFile.FileName;
这种语法
Info myPath = new Info()
{
path = oFile.FileName
};
只是一个快捷方式,可以更具可读性,但会做同样的事情。实际上它似乎是从VisualBasic(With
语句)中获取的。
解释上述语法:
YourClassName <your_variable> = new YourClassName()
{
<property_name> = value,
<anotherProperty> = value,
...
<last_property> = value
};
最后一种方法是使用一个构造函数,将路径作为参数并初始化它。这实际上是cpu执行的操作较少的方式(但并不重要)。
答案 1 :(得分:3)
该构造是object initializer。它不是任意语句的列表 - 它只是 字段和属性的初始化,它们以逗号分隔:
Foo x = new Foo // Implicitly calls the parameterless constructor
{
Property1 = value1,
Property2 = value2
};
这是简写:
Foo tmp = new Foo();
tmp.Property1 = value1;
tmp.Property2 = value2;
Foo x = tmp;
在C#3中引入了对象初始化程序,以及集合初始化程序,它们是重复调用Add
的有效语法糖。所以:
List<string> names = new List<string>
{
"Foo", "Bar"
};
相当于:
List<string> tmp = new List<string>();
tmp.Add("Foo");
tmp.Add("Bar");
List<string> names = tmp;
答案 2 :(得分:2)
在C#3.0中,他们添加了一个新的&amp;将对象初始化为单个语句/表达式的有用功能。
以前,您必须发出单独的声明:
Info myPath = new Info();
myPath.Filename = ...
myPath.AnotherProperty = ...
myPath.AnotherAnotherProperty = ...
您现在可以在一个步骤中执行相同的分配:
Info myPath = new Info
{
Filename = ...
AnotherProperty = ...
AnotherAnotherProperty = ...
};
这对于在Linq查询中构造对象非常有用(无需自定义代码对象构造函数)。
例如:
someList.Select(x => new SomethingElse{ SomeProperty = x.Something });
答案 3 :(得分:1)
Info myPath = new Info()
{
path = oFile.FileName
};
表示: 初始化一个新的Info类,并向属性路径添加值oFile.FileName 它是以下的简短版本:
Info myPath = new Info();
myPath.path = oFile.FileName;
你不需要&#39;;&#39;因为您可以在括号中堆叠更多属性,如下所示:
Person p = new Person()
{
Name = "John",
Age = 25
};
答案 4 :(得分:0)
这是在C#中初始化变量的新方法。你也可以跳过'()'标志。 您可以在括号中初始化列表,数组等,您必须插入要在对象中初始化的元素。
答案 5 :(得分:0)
Info myPath = new Info()
{
path = oFile.FileName
};
相当于
Info myPath = new Info();
myPath.path = oFile.FileName;
使用对象初始化结构进行初始化时,可以按照您的说明创建属性分配列表。这样,您可以在一次调用中创建对象并分配变量,而无需显式构造函数。上面的内容很容易写成一行。
可以找到更多信息on the MSDN website。
答案 6 :(得分:0)
C#允许您在构建对象的同时初始化对象的属性。
这些都是等价的:
var foo = new Foo();
foo.Property = "Bar";
foo.AnotherProperty = 12;
var foo = new Foo()
{
Property = "Bar",
AnotherProperty = 12
};
// The parentheses are not really necessary for parameterless constructors
var foo = new Foo
{
Property = "Bar",
AnotherProperty = 12
};