gpt4 book ai didi

C#动态选择字符串列表

转载 作者:IT王子 更新时间:2023-10-29 04:53:51 26 4
gpt4 key购买 nike

我正在尝试获取 List我的动态对象列表中的字符串,它一直在说:

Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<dynamic>' to 'System.Collections.Generic.List<string>'

我正在选择一个属性并使用 .ToString()在上面:

var objects = new List<dynamic>();
//filling objects here

List<string> things = objects.Select(x => x.nameref.ToString()).ToList();

那么它不是一个有效的字符串列表吗?为什么编译器假定此列表的类型为 dynamic

我也试过从 this 转换回答,但它一直给我同样的错误。

谁知道怎么做List<string>

编辑:

为什么它不起作用?因为你可以像这样制造困惑:

public class Test
{
public int ToString()
{
return 0;
}
}

编译器不知道ToString是否存在返回 stringint .

最佳答案

你需要施放元素,像这样:

List<string> things = objects.Select(x => x.nameref.ToString()).Cast<string>().ToList();

它不能识别 ToString() 返回字符串的原因是它是在 dynamic 对象上调用的,并且方法绑定(bind)是在运行时完成的,而不是编译时间。

关于C#动态选择字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34173163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com