类的运行时属性和名称

时间:2012-07-24 06:54:24

标签: c# reflection

我有一个班级

public class ProjectTask
{
    public ProjectTask();


    [XmlElement("task_creator_id")]
    public string task_creator_id { get; set; }
    [XmlElement("task_owner_id")]
    public string task_owner_id { get; set; }
    [XmlElement("task_owner_location")]
    public TaskOwnerLocation task_owner_location { get; set; }
    [XmlElement("task_owner_type")]
    public string task_owner_type { get; set; }
    [XmlElement("task_type_description")]
    public string task_type_description { get; set; }
    [XmlElement("task_type_id")]
    public string task_type_id { get; set; }
    [XmlElement("task_type_name")]
    public string task_type_name { get; set; }
}

xml将在运行时反序列化。

有没有办法获得字段名称和值?

使用反射我可以获得如下的属性名称:

PropertyInfo[] projectAttributes = typeof(ProjectTask).GetProperties();

可以应用foreach循环来获取属性

foreach(PropertyInfo taskName in projectAttributes)
       {
           Console.WriteLine(taskName.Name);
       }

但是如何打印属性和值? 喜欢     task_creator_id = 1

其中task_Id是其中一个属性,运行时的值为1。

2 个答案:

答案 0 :(得分:1)

使用taskName.GetValue(yourObject,null)

其中yourObject应为ProjectTask的实例。例如,

ProjectTask yourObject = (ProjectTask)xmlSerializer.Deserialize(stream)

var propDict = typeof(ProjectTask)
                  .GetProperties()
                  .ToDictionary(p => p.Name, p => p.GetValue(yourObject, null));

答案 1 :(得分:1)

您可以使用PropertyInfo对象执行此操作:

var propertyName = MyPropertyInfoObject.Name;
var propertyValue = MyPropertyInfoObject.GetValue(myObject, null);

使用foreach循环可以访问所有类型的属性,也可以使用知道其名称的specefic属性,如下所示:

var MyPropertyInfoObject = myType.GetProperty("propertyName");
相关问题