首页 > 解决方案 > 如何获取属性的值

问题描述

大家好,我遇到了下一个问题:

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;
}

标签: c#entity-frameworklinqentity-framework-6entity-framework-4

解决方案


您可以覆盖 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;
    }
}

推荐阅读