1 回答

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,我只是澄清我的“什么也不做”聲明。
- 1 回答
- 0 關注
- 199 瀏覽
添加回答
舉報