【发布时间】:2010-11-18 06:46:07
【问题描述】:
我是不是想错了?或者遗漏了一些完全明显的东西?我最好举个例子。这段代码是我现在初始化一个新对象的方式。这似乎是多余的。
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Person(int Id)
{
XDocument personXml = XDocument.Load("person.xml");
var person = (from p in personXml.Descendants("Person")
where (int)p.Attribute("id") == Id
select new
{
FirstName = (string)p.Element("FirstName"),
LastName = (string)p.Element("LastName"),
Age = (int)p.Element("Age")
}).SingleOrDefault();
//with the "select new" in query I have to set the properties manually
FirstName = person.FirstName;
LastName = person.LastName;
Age = person.Age;
}
}
这就是我正在尝试做的,但无法让它发挥作用:
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public Person(int Id)
{
XDocument personXml = XDocument.Load("person.xml");
(from p in personXml.Descendants("Person")
where (int)p.Attribute("id") == Id
select
{
FirstName = (string)p.Element("FirstName"),
LastName = (string)p.Element("LastName"),
Age = (int)p.Element("Age")
}).SingleOrDefault();
}
}
我觉得应该有一种方法来完成我正在尝试做的事情。我一定错过了一些句法或基本的理解,为什么它没有。或者也许我只是疯狂地认为应该这样做。
【问题讨论】:
标签: c# linq oop constructor