c# - 如何获取属性的值
问题描述
大家好,我遇到了下一个问题:
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;
}
}
推荐阅读
- javascript - 从中间网站重定向获取位置
- java - 将 Jsch 与 InputStream 一起使用会引发 NullPointerException
- php - php if 在 windows 和 linux 中的行为不同
- swiftui - SwiftUI - ScrollViewReader 滚动到顶部,包括填充(锚点加常量)
- jenkins - 詹金斯在舞台级别的发布操作受 buildResult 的影响
- image-processing - INTA图像的批量转换
- animation - 使用 JAVA FX 旋转图像
- python - 如何在 python 中从 twitter 中的用户数据字典中获取/访问“名称”属性?
- angular - angular2+:如何遍历三态(不确定)复选框的值
- python - 自定义MongoDB类的模拟方法