[英]c# how to return empty object of user defined type?
I have a method that deserialize XML to Particular user defined type (Product Class). 我有一个方法将XML反序列化为特定用户定义的类型(产品类)。
public Class Product
{
public int ID{ get; set; }
public string ModelNumber { get; set; }
public string SKU { get; set; }
public string Att4 { get; set; }
public string Att5 { get; set; }
}
This Method will accept XML Object and read it's properties and return a product class. 此方法将接受XML对象并读取其属性并返回产品类。 I have a condition when the XML is empty I want to return an empty object like this {}.
我有条件当XML为空时我想返回一个像{}这样的空对象。 Here is my deserialize method :
这是我的反序列化方法:
public static Product DeserializeXmlAsParentProduct(object xml)
{
if (xml == DBNull.Value)
return // I want to return {};
var doc = XDocument.Parse(xml.ToString());
var product = doc.Descendants("row").Select(pd => new Product
{
ID = GetValue<int>(pd.Element("ID")),
ModelNumber = GetValue<string>(pd.Element("ModelNumber")),
SKU = GetValue<string>(pd.Element("SKU"))
})
.ToList().FirstOrDefault();
return product;
}
My in put XML will look like this when a value is retrieved from the DB : 当从数据库中检索到值时,我的输入XML将如下所示:
<root>
<row>
<ID>8</ID>
<ModelNumber>GT</ModelNumber>
<SKU>UR</SKU>
<row/>
</root>
How Can I return empty object if the condition is met ? 如果满足条件,如何返回空对象?
Also If every thing went fine. 如果一切顺利的话。 It will return for me a product class with all the attributes.
它将为我返回一个包含所有属性的产品类。
{ID, ModelNumber, SKU, Att4, Att5}`
How can I use LINQ to return only the first three attributes only ? 如何使用LINQ仅返回前三个属性? like this :
像这样 :
{ID, ModelNumber, SKU}
I was thinking of using dynamic object. 我在考虑使用动态对象。 Is there any Other way to achieve this?.
有没有其他方法来实现这一目标?
Any Help is appreciated. 任何帮助表示赞赏。
Using Linq to construct anonymous instances: 使用Linq构建匿名实例:
var anonResults = list.Select( p => new {p.ID, p.ModelNumber, p.SKU });
However, in this example you cannot return
anonResults
. 但是,在此示例中,您无法
return
anonResults
。 Anonymous classes are only valid in the scope in which they are first declared. 匿名类仅在首次声明它们的范围内有效。
If you really want to do this dynamically, javascript style, I would use ExpandoObject 如果你真的想动态地执行这个javascript样式,我会使用ExpandoObject
My recommendation is just return the full object. 我的建议只是返回完整的对象。 If you want to restrict access to
Att4
and Att5
, consider implementing an interface on Product
that only declares ID
, ModelNumber
and SKU
: 如果要限制对
Att4
和Att5
访问 ,请考虑在Product
实现仅声明ID
, ModelNumber
和SKU
:
public interface IProduct
{
int ID{ get; set; }
string ModelNumber { get; set; }
string SKU { get; set; }
}
public Class Product : IProduct
{
public int ID{ get; set; }
public string ModelNumber { get; set; }
public string SKU { get; set; }
public string Att4 { get; set; }
public string Att5 { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.