亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我不能在 C# 中創建匿名類型的 list<T> ?

為什么我不能在 C# 中創建匿名類型的 list<T> ?

C#
喵喵時光機 2023-07-09 16:44:19
我是 c# 新手anonymous types,我想創建一個包含 3 個變量的變量list:,?,?。anonymous typesstring strint numDataTime time我使用了一個簡單的方法Console application來做到這一點,我想我得到了錯誤,因為我沒有System.Core,因為上面問題的評論中有人說:(當然,您還需要對 System.Core 的引用。)我不知道是什么System.Core以及我是否有它,所以這可能是問題所在我確實用Systme.Linq。這是代碼:var?list?=?new[]?{?str,?num,?time?}.ToList(); list.add("hi",?5,?DateTime.Now); Console.WriteLine(list[0].num);當我嘗試指定type例如 的variables?時,我也遇到問題string str。
查看完整描述

1 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

您缺少一些語法。匿名類型必須用 聲明new{...}當無法通過變量名稱推斷屬性名稱時,必須聲明屬性名稱。(你也有一個拼寫錯誤Add;它應該是大寫的)。

以下:

var str = "string";

var num = 5;

var time = DateTime.UtcNow;

// notice double "new"?

// property names inferred to match variable names

var list = new[] { new { str, num, time } }.ToList();?


// "new" again. Must specify property names since they cannot be inferred

list.Add(new { str = "hi", num = 5, time = DateTime.Now });


Console.WriteLine(list[0].num);

話雖如此,這相當笨重。我建議編寫一個具有您想要的屬性的類,或者使用ValueTuple.

這有效并且更清晰/干凈:

var list = new List<(string str, int num, DateTime time)>();


// ValueTuple are declared in parens, method calls require parens as well

// so we end up with two sets of parens, both required?

list.Add((str, num, time));

list.Add(("hi", 5, DateTime.Now));


Console.WriteLine(list[0].num);

更喜歡自己的類的另一個原因ValueTuple是您不能將方法聲明為接受匿名類型。換句話說,這樣的東西是無效的:


public void DoSomethingWithAnonTypeList(List<???> theList ) { ... }?

沒有什么*我可以用來替換,???因為匿名類型都是internal并且具有“難以形容的”名稱。你將無法傳遞你的清單并用它做一些有意義的事情。那么有什么意義呢?


相反,我可以聲明一個方法接受 s 列表ValueTuple:


public void DoSomethingWithTupleList(List<(string, int, DateTime)> theList) {?

? ? ?Console.WriteLine(theList[0].Item1);

}?

或使用命名元組:


public void DoSomethingWithTupleList(List<(string str, int num, DateTime time)> theList) {?

? ? ?Console.WriteLine(theList[0].time);

}?

* 從技術上講,您可以將匿名類型列表傳遞給泛型方法。但是您將無法訪問各個屬性。您能做的最好的事情就是訪問列表Count或迭代列表/可枚舉,也許打印默認值ToString,這也并沒有給您帶來太多幫助。這里沒有通用的約束可以提供幫助。此方法中的第三條語句將生成編譯器錯誤:


public void DoSomethingGenerically<T>(List<T> theList) {


? ? ? Console.WriteLine(theList.Count); // valid

? ? ? Console.WriteLine(theList[0]); // valid, prints default ToString


? ? ? Console.WriteLine(theList[0].num); // invalid! What's the point?


}


var list = new[] { new { str = "hi", num = 5, time = DateTime.Now } }.ToList();

// valid due to type inference, but see comments above

DoSomethingGenerically(list);?

請注意,您也會遇到同樣的問題ValueTuple,我只是澄清我的“什么也不做”聲明。


查看完整回答
反對 回復 2023-07-09
  • 1 回答
  • 0 關注
  • 199 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號