[英]How to get a value of a property
您好,我遇到下一個問題:
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;}
}
想象一下我擁有這個域,我想復制Document的所有原始屬性以及非原始屬性,例如Header和Footer,我只需要文本。
我有下一個代碼只是要復制原始屬性:
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;
}
您可以在非原始類型上重寫 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.