簡體   English   中英

如何從動態轉換的 class 中獲取子成員值?

[英]how to get child members value from dynamically casted class?

好吧,我想從動態轉換的 class 中獲取 class 成員值,但我找不到它的子 class 成員值。
現在我正在獲取 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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM