如何從主類循環子類屬性?如何從主類循環子類屬性?
public class GroupA
{
public string FullName = "", BirthDay = "";
}
public class GroupB
{
public string Email = "";
}
public class GroupC
{
public string Phone;
}
public class MainGroup
{
public GroupA GroupA;
public GroupB GroupB;
public GroupC GroupC;
}
protected void Page_Load(object sender, EventArgs e)
{
GroupA NewGroupA = new GroupA();
NewGroupA.FullName="TEST MASTER";
NewGroupA.BirthDay="02/20/1984";
GroupB NewGroupB = new GroupB();
NewGroupB.Email="[email protected]";
GroupC NewGroupC=new GroupC();
NewGroupC.Phone="555 123 4567";
//Assign new class instances to the main class
MainGroup NewMainGroup= new MainGroup();
NewMainGroup.GroupA=NewGroupA;
NewMainGroup.GroupB=NewGroupB;
NewMainGroup.GroupC=NewGroupC;
//Loop through the main class
foreach (var Group in typeof(MainGroup).GetFields())
{
Response.Write("<BR>MainGroupName= " + Group.Name + " Value= " + Group.GetValue(NewMainGroup).ToString());
//PROBLEM IS HERE. Can't loop through the subclass We need to display the GroupA, GroupB, GroupC below.
foreach (var SubGroup in Group)
{
Response.Write("<BR>");
}
}
}
現在看來似乎返回null變量。 ());}};}}(){0}(){0}這個函數返回一個新的數組。 Response.Write(「
變量值NULL HERE」+ SubGroup.GetValue(SubGroup).ToString()+「Value =」); } – SMTPGUY01 2011-05-28 14:18:30
對不起,讓我重寫一個正確的答案...只是給我一秒。 – Alxandr 2011-05-28 14:34:05
更新你的問題。你問如何循環一個類的屬性。這些都不是屬性。屬性具有get-set訪問器。請參閱:http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx BTW:您應該使用屬性而不是字段來處理這些類型的信息。 – MikeTeeVee 2011-05-28 15:07:04