【问题标题】:Cannot implicitly convert type 'string' to 'int' array无法将类型“string”隐式转换为“int”数组
【发布时间】:2014-07-28 19:52:53
【问题描述】:
public class Product
{
    public string name { get; set; }
    public string description { get; set; }
    public decimal price { get; set; }
    public int   [] categories { get; set; }
}

var parentstl = from parentstyle in DBB.vParentStyles
                select new
                {
                    parentstyle.name,
                    parentstyle.description,
                    parentstyle.price,
                    Categories = parentstyle.categories.ToArray(),
                };

foreach (var pstl in parentstl)
{
    request.AddBody(new Product
    {
        name = pstl.name,
        description = pstl.description,
        price = (Decimal)pstl.price,
        **categories = new int[]{pstl.categories}.ToArray()**
    });
}

我收到此错误:错误 1 ​​无法将类型 'string' 隐式转换为 'int'。

我该如何解决这个问题?谢谢。

【问题讨论】:

  • int.ParseConvert.ToInt32.
  • 我很惊讶它竟然走到了这一步,因为你的匿名类型中有Categories,但你在后面的块中使用了categories。如果您提供一个简短但完整的程序,格式正确...
  • 你的parentstyle是什么类型的?
  • parentstyle.categories 元素是否可以转换为 int?

标签: c# json


【解决方案1】:

你可以使用 Linq,改变这个:

**categories = new int[]{pstl.categories}.ToArray()**

到这里:

categories = pstl.categories.Select(int.Parse).ToArray();

【讨论】:

  • Select(int.Parse) 可以正常工作,不需要额外的 lambda
  • 是的,它肯定会。我希望写出来能给出一个清晰的解释
  • 它给了我这个错误:错误 1 ​​The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' 不能从用法中推断出来。尝试明确指定类型参数。
  • 我需要这样的输出。但是我得到一个错误“System.Linq.Enumerable.Select(System.Collections.Generic.IEnum‌​erable, System.Func)”不能从用法中推断出来。尝试明确指定类型参数 Preferred Output:Value = "{\"name\":\"000TEST\",\"description\":\"This is Test Item\",\"price\":\ "19.99\",\"categories\":[141,163],\"type\":\"physical}"
猜你喜欢
  • 1970-01-01
  • 2013-06-03
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多