c#和反射的使用

本文关键字:反射的 | 更新日期: 2023-09-27 18:13:14

我浏览了这个网站(http://snipplr.com/view.php?codeview&id=17637),它像这样说明了反射的使用:

public class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
   private void button2_Click_1(object sender, EventArgs e)
    {
        var person = new Person { Age = 30, Name = "Tony Montana" };
        var properties = typeof(Person).GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine("{0} = {1}", property.Name, property.GetValue(person, null));
        }
    }

上面的代码片段会给你:年龄:30姓名:Tony Montana

如果我们像这样将"Kid"添加到"AnotherPerson"类中呢

    public class Kid
    {
        public int KidAge { get; set; }
        public string KidName { get; set; }
    }
    public class AnotherPerson
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public Kid Kid { get; set; }
    }

这片段;

private void button3_Click(object sender, EventArgs e)
    {
        var anotherPerson = new AnotherPerson { Age = 30, Name = "Tony Montana", Kid = new Kid { KidAge = 10, KidName = "SomeName" } };
        var properties = typeof(AnotherPerson).GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine("{0} = {1}", property.Name, property.GetValue(anotherPerson, null));
        }
    }

给我:年龄:30姓名:托尼·蒙大拿孩子:ProjectName。Form1 +孩子

不是我想要的....我也可以使用反射来迭代"Kid"吗?建议吗?

c#和反射的使用

可以有一个像这样的辅助方法吗?

public List<KeyValuePair<string, object>> GetPropertiesRecursive(object instance)
{
  List<KeyValuePair<string, object>> propValues = new List<KeyValuePair<string, object>>();
  foreach(PropertyInfo prop in instance.GetType().GetProperties())
  {
    propValues.Add(new KeyValuePair<string, object>(prop.Name, prop.GetValue(instance, null));
    propValues.AddRange(GetPropertiesRecursive(prop.GetValue(instance));
  }
}

Call as - GetPropertiesRecursive(anotherPerson)

    var anotherPerson = new AnotherPerson { Age = 30, Name = "Tony Montana", Kid = new Kid { KidAge = 10, KidName = "SomeName" } };
    var properties = typeof(AnotherPerson).GetProperties();
    foreach (PropertyInfo property in properties)
    {
        if (property.PropertyType == typeof(Kid)){
            var pp = typeof(Kid).GetProperties();
            Console.WriteLine("Kid:");
            foreach (PropertyInfo p in pp)
            {
                Console.WriteLine("'t{0} = {1}", p.Name, p.GetValue(anotherPerson.Kid, null));
            }
        }
        else
            Console.WriteLine("{0} = {1}", property.Name, property.GetValue(anotherPerson, null));
    }

代码循环遍历属性并使用ToString(通过Console.WriteLine使用的String.Format方法)获得属性值的字符串表示。

如果你想改变Kid属性值的显示方式,你基本上有两个选择:

  1. 检查反射代码中的属性类型(property.PropertyType),以便您可以为Kid类型做一些不同的事情。

  2. Kid类中重写ToString方法,以便它返回您想要显示为值的任何字符串。

递归方法可以获得属性中的属性值:

public static string GetProperties(object obj)
{
    var t = obj.GetType();
    var properties = t.GetProperties();
    var s = "";
    foreach (PropertyInfo property in properties)
    {
        object propValue = property.GetValue(obj, new object[0]);
        string propertyToString;
        if (t.GetMethod("ToString").DeclaringType != typeof(object))
            propertyToString = propValue.ToString();
        else if (typeof(IConvertible).IsAssignableFrom(property.PropertyType))
            propertyToString = Convert.ToString(propValue);
        else
            propertyToString = GetProperties(propValue);
        s += string.Format("'{0}' = '{1}'", property.Name, propertyToString);
    }
    return s;
}

如果你有实际的目的,JSON(或其他)序列化可能更合适,例如,使用JSON.net将产生一个类似的字符串