简体   繁体   中英

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM