[英]How to get a value of a property
Hello people i'm with the next problem: 您好,我遇到下一个问题:
public class Document
{
public Header Header {get;set;}
public Footer Footer{get;set;}
public string Text{get;set;}
public string Description{get;set;}
public int NumberOfPages{get;set;}
}
public class Header
{
public int Id{get;set;}
public string Text{get;set;}
}
public class Footer
{
public int Id{get;set;}
public string Text{get;set;}
}
Imagine i have this domain, i will like to copy all the primitive properties of Document and the ones that aren't primitive, such as Header and Footer i would like just the text. 想象一下我拥有这个域,我想复制Document的所有原始属性以及非原始属性,例如Header和Footer,我只需要文本。
I have the next code just to copy the properties which are primitive: 我有下一个代码只是要复制原始属性:
public static List<DataPropertyReport> GetPrimitiveProperties<T>(T entity)
{
var properties = entity.GetType().GetProperties();
List<DataPropertyReport> info = new List<DataPropertyReport>();
foreach (var property in properties)
{
Object value = property.GetValue(entity, null);
Type type = value != null ? value.GetType() : null;
if (type != null &&
(type.IsPrimitive ||
type == typeof(string) ||
type.Name == "DateTime"))
{
var name = property.Name;
info.Add(new DataPropertyReport(name, value.ToString(), 1));
}
}
return info;
}
You could override ToString()
on the non-primitive types and just call that overload: 您可以在非原始类型上重写
ToString()
,然后调用该重载:
public class Header
{
public int Id { get; set; }
public string Text { get; set; }
public override string ToString()
{
return Text;
}
}
public class Footer
{
public int Id { get; set; }
public string Text { get; set; }
public override string ToString()
{
return Text;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.