我有一個物件,裡面屬性名稱重複性很高,所以想說用回圈把物件裡面的值抓出來就好,不需要寫很多行。

物件內容如下:

 

public class TestObject
{
    public Bool Item1Selected;
    public Bool Item1Accepted;
    public Bool Item2Selected;
    public Bool Item2Accepted;
    public Bool Item3Selected;
    public Bool Item3Accepted;
    public Bool Item4Selected;
    public Bool Item4Accepted;
    public string ID;
    public string FULLNAME;

    public TestObject()
    {

        Item1Selected
            = Item1Accepted
            = Item2Selected
            = Item2Accepted
            = Item3Selected
            = Item3Accepted
            = Item4Selected
            = Item4Accepted
            = False;

        ID
            = FULLNAME
            = "";
    }
}
 

使用範例:

 

private void LoadData(List<TestObject> tData)
{
            foreach (TestObject vTO in tData)
            {
                for (int index = 1; index <= tData.Count; index++)
                {
                    Bool vSelectedValue = vTO.GetType().GetField("Item" + index.ToString() + "Selected").GetValue(vTO);
                    Bool vAcceptedValue = vTO.GetType().GetField("Item" + index.ToString() + "Accepted").GetValue(vTO);
                }
            }
}

 

PS: GetProperty("Item1Selected").GetValue(vCT, null)

文章標籤
全站熱搜
創作者介紹
創作者 ❤ Saori さおり ❤ 的頭像
❤ Saori さおり ❤

♥單純是種快樂♥

❤ Saori さおり ❤ 發表在 痞客邦 留言(0) 人氣(42)