我在获取一个属性是另一个类的类的值时遇到了问题。
下面是一个示例:
public class Person
{
private int age;
private string name;
public Person()
{
Address = new Address();
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public Address Address { get; set; }
}
public class Address
{
public string street { get; set; }
public string houseno { get; set; }
}
public class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Age = 27;
person.Name = "Fernando Vezzali";
person.Address.houseno = "123";
person.Address.street = "albert street";
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.GetValue(person, null));
}
}
}
但是这样我就得不到地址值。
有人能帮帮忙吗?
发布于 2009-09-28 22:24:53
type.GetProperties()
仅获取类型的的属性,其中之一是对象Address
。street
和houseno
不是Person
上的属性。
Console.Write...
对每个参数隐式调用ToString()
。因此,您可能会看到"Address - Namespace.Address“作为输出,因为someAddressObject.ToString()
将返回类型名。
要在这种特定情况下获得所需内容,最简单的方法是覆盖Address
对象上的ToString()
,以输出该对象的一些有意义的字符串表示:
public override ToString()
{
return string.Format("#{0} {1}",
this.houseno,
this.street); //returns #123 StreetName
}
如果您实际上需要编写对象上每个子对象的每个属性,这可能会变得相当复杂-您实际上是在谈论序列化,它沿着对象树递归到每个对象中。
发布于 2009-09-28 22:28:07
这里是可能的ToString,考虑到Jason的答案...
您还可以将返回的反射对象转换为一个地址,以访问完整的对象和属性
public class Address
{
public string street { get; set; }
public string houseno { get; set; }
public override ToString() {
return string.Format("street: {0}, house: {1}", street, houseno);
}
}
发布于 2009-09-28 22:25:16
如果您对返回格式化字符串作为Address的值感到满意,那么您需要在Address中实现ToString(),或者您的迭代代码需要检查每个属性,以确定该属性的类型是否也公开了属性,并将其排队以供进一步检查。
https://stackoverflow.com/questions/1489668
复制相似问题