类的嵌套属性的C#反射
我想知道如何获得C#中属性的值,但该属性是另一种类型类的嵌套属性的C#反射,c#,linq,linq-to-sql,reflection,properties,C#,Linq,Linq To Sql,Reflection,Properties,我想知道如何获得C#中属性的值,但该属性是另一种类型 public class Customer { public string Name {get; set;} public string Lastname {get; set;} public CustomerAddress Address {get; set;} } 所以我可以得到Name和LastName的属性值,但是我不知道如何得到CustomerAddress.City的值 这就是我到目前为止所拥有的 public
public class Customer
{
public string Name {get; set;}
public string Lastname {get; set;}
public CustomerAddress Address {get; set;}
}
所以我可以得到Name和LastName的属性值,但是我不知道如何得到CustomerAddress.City的值
这就是我到目前为止所拥有的
public object GetPropertyValue(object obj, string property)
{
if (string.IsNullOrEmpty(property))
return new object { };
PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
然后在LINQ语句中使用此方法
var cells = (from m in model
select new
{
i = GetPropertyValue(m, key),
cell = from c in columns
select reflection.GetPropertyValue(m, c)
}).ToArray();
因此,CustomerAddress没有任何价值
任何帮助都将不胜感激
****更新****
这是我如何做到的
public object GetNestedPropertyValue(object obj, string property)
{
if (string.IsNullOrEmpty(property))
return string.Empty;
var propertyNames = property.Split('.');
foreach (var p in propertyNames)
{
if (obj == null)
return string.Empty;
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(p);
if (info == null)
return string.Empty;
obj = info.GetValue(obj, null);
}
return obj;
}
首先,如果您想获取
CustomerAddress.City
的值,您永远不会得到它CustomerAddress
是类型,而不是属性名称。您想获取地址.城市
也就是说,您的GetPropertyValue
没有设置为执行您想要的操作
尝试将名称按点拆分:
var-propertyNames=property.split('.')代码>
现在,您有了一个财产名称列表{“地址”,“城市”}
然后,可以逐个循环这些属性名,递归调用GetPropertyValue
应该可以了:)@Michael->倒过来的部分;-)
设置嵌套属性的值如何?(与此相同,但对于info.SetValue…?)这是完全无用的,它甚至没有简单的类型转换。它也不会创建父对象的新实例。在foreach中的第二次迭代中将有一个null引用。这根本不起作用,仅适用于字符串,并且仅当它不是复杂类型时。
public static void SetNestedPropertyValue(object obj, string property,object value)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (string.IsNullOrEmpty(property))
throw new ArgumentNullException("property");
var propertyNames = property.Split('.');
foreach (var p in propertyNames)
{
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(p);
if (info != null)
{
info.SetValue(obj, value);
return;
}
}
throw new KeyNotFoundException("Nested property could not be found.");
}