如何从动态转换类中获取子成员值?

时间:2012-04-04 10:28:36

标签: c# asp.net dynamic casting

我想从一个动态的类中获取类成员值,但是我无法找到它的子类成员值。
现在我获得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;
    }
  }     
}

1 个答案:

答案 0 :(得分:0)

您可以获取属性的类型,然后使用此类型,就像在代码的开头一样。

foreach( var memberInfo in members )
{
  propertyInfo = types.GetProperty( memberInfo.Name );
  if( propertyInfo != null )
  {
     Console.WriteLine( propertyInfo.PropertyType ); 
     // type of every property
  }
}