iT邦幫忙

1

C# List<T> Add 問題

  • 分享至 

  • xImage

大家好 今天對於型態上有一些問題想詢問
這是我其中一個class

    public class CLD243_Content
    {
        [Slapper.AutoMapper.Id]
        public string INQIDN { get;set; }
        [Slapper.AutoMapper.Id]
        public string INQNAM { get;set; } 

        public List<GUR_Data> GUR { get; set; }
    }

這是我另外一個class

    public class test_info
    {
        public string subtotal_1 { get; set; }

        public string subtotal_2 { get; set; }  

        public List<CLD243_Content> content { get; set; }
    }

當我下SQL資料會塞入List<CLD243_Content>,接著我要對資料進行一些處理和運算
所以我又下了foreach 要將資料進行分類。
我要將List<CLD243_Content>的第0筆資料塞入test_info底下的content於是我宣告test_info一個是List一個是暫時存取資料,並且進行foreach塞入剛剛SQL回傳回來的List<CLD243_Content>。
https://ithelp.ithome.com.tw/upload/images/20220710/20127159ucbJ7ApH7T.png

//最後整理完畢的結果
List<test_info> testList = new List<test_info>();
//暫時存取資料
test_info test_Info = new test_info();  
//處理邏輯
foreach(var items in CLD243_content)
{
    test_Info.content.Add(items);
    test_Info.content[0] = items;
}

https://ithelp.ithome.com.tw/upload/images/20220710/201271598Wp7KPsVFh.png
這兩種塞入值我都得到並未將物件參考設定為物件的執行個體。

我想請問各位我是不是哪裡理解錯誤了
還請各位指教 抱歉

看更多先前的討論...收起先前的討論...
canrong iT邦新手 3 級 ‧ 2022-07-10 21:03:38 檢舉
你建立了該物件但卻沒有將裡面的全域變數初始化,所以你的content = null,你至少應該在使用前配置它。
Mikey iT邦新手 5 級 ‧ 2022-07-10 21:18:55 檢舉
@canrong 您好,謝謝您的回答,不好意思 不太懂說我要怎麼在使用前配置它?我已經建立了物件,但是我要裡面的content要去塞入資料,意思是說我要在宣告裡面的content這樣嘛?
canrong iT邦新手 3 級 ‧ 2022-07-10 21:25:48 檢舉
要看你怎麼設計 如果不想在程式額外配置它,那就寫在建構子內,在你new該物件時配置它們給予它們初始值。
canrong iT邦新手 3 級 ‧ 2022-07-10 21:36:02 檢舉
當你在使用get與set存取子時你可能需要稍微了解它的運作方式。
https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/classes-and-structs/using-properties
建構子的例子可以參考微軟的文件
https://docs.microsoft.com/zh-tw/dotnet/csharp/fundamentals/object-oriented/objects
柴幫客 iT邦新手 5 級 ‧ 2022-07-10 22:03:41 檢舉
直接用
test_info.Add(items);
Homura iT邦高手 1 級 ‧ 2022-07-11 00:40:37 檢舉
使用物件要先new啊!0.0
Mikey iT邦新手 5 級 ‧ 2022-07-11 21:36:20 檢舉
@canrong 謝謝您的協助,讓我有了解到我出錯的問題!
Mikey iT邦新手 5 級 ‧ 2022-07-11 21:36:52 檢舉
@柴幫客 謝謝您 但是我有嘗試過這方法會是錯誤的
Mikey iT邦新手 5 級 ‧ 2022-07-11 21:37:32 檢舉
@Homura 謝謝您的答覆,我以為只要宣告最外層的new 就等於裡面都宣告了,經過大家的解釋我了解到了我的問題。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
小魚
iT邦大師 1 級 ‧ 2022-07-10 22:16:50
最佳解答

建構式要先初始化

public class test_info
{
    public string subtotal_1 { get; set; }

    public string subtotal_2 { get; set; }  

    public List<CLD243_Content> content { get; set; }
    
    public test_info()
    {
        test_Info.content = new List<CLD243_Content>();
    }
}
Mikey iT邦新手 5 級 ‧ 2022-07-11 21:39:00 檢舉

Hi 小魚大大,
謝謝您熱心的回覆,最終我宣告了建構式解決了這項問題。

public test_info(){
content = new List<CLD243_Content>();
}

感謝您!

我要發表回答

立即登入回答