如何从动态铸造类中获取子成员值
本文关键字:获取 成员 动态 | 更新日期: 2023-09-27 18:30:02
我正在字符串中从动态转换的类中获取类成员值,但找不到它的子类成员值
现在我正在获取TotalWeight成员属性,但我也想获取AnotherClass的子成员属性,如AnotherClass.child。如何获取这些成员?
string ClassName="something";
Type types = Type.GetType(ClassName, false);
var d = from source in types.GetMembers().ToList()
where source.MemberType == MemberTypes.Property
select source;
List<MemberInfo> members = d.Where(memberInfo =>
d.Select(c => c.Name)
.ToList()
.Contains(memberInfo.Name))
.ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
if (myobj.GetType().GetProperty(memberInfo.Name) != null)
{
value = myobj.GetType()
.GetProperty(memberInfo.Name)
.GetValue(myobj, null);
//how to get child members value here?
}
}
//Where class something has member
public class something
{
private decimal _totalWeight;
private Anotherclass _another;
public decimal TotalWeight
{
get
{
return this._totalWeight;
}
set
{
this._totalWeight = value;
}
}
public Anotherclass Another
{
get
{
return this._another;
}
set
{
this._another= value;
}
}
}
您可以获取属性的类型,然后在代码开始时使用此类型。
foreach( var memberInfo in members )
{
propertyInfo = types.GetProperty( memberInfo.Name );
if( propertyInfo != null )
{
Console.WriteLine( propertyInfo.PropertyType );
// type of every property
}
}