【问题标题】:unhandled exception of type 'System.InvalidCastException' occurred...Unable to cast object of type 'System.String' to type发生“System.InvalidCastException”类型的未处理异常...无法将“System.String”类型的对象转换为类型
【发布时间】:2017-05-17 11:56:58
【问题描述】:

有人可以帮帮我吗?按照我的代码和“GelatoProject.exe 中发生‘System.InvalidCastException’类型的未处理异常

附加信息:无法将“System.String”类型的对象转换为“GelatoProject.RecipeVariables”类型。”是消息。

// ...
using (var db = new GelatoProjectDBEntities())
{
    RecipeVariables selected = 
        (RecipeVariables)comboBoxRecipeDetail.SelectedItem;

    var results = (from x in db.Recipe_Parameters
                select new RecipeVariables 
                        { 
                            Id = x.Id, 
                            RecipeDetail = x.recipeDetail, 
                            Parameter = x.parameter, 
                            RangeDetail = x.rangeDetail, 
                            RangeValue = x.value.ToString() 
                        }
               )
                .Where(x => x.RecipeDetail == selected.RecipeDetail && x.Parameter == "totalsolids" && x.RangeDetail == "Max")
                .FirstOrDefault();

    totsolidsRangeMax = decimal.Parse(results.RangeValue);

    MessageBox.Show(totsolidsRangeMax.ToString());
}
// ...

class RecipeVariables
{
    public int Id { get; set; }
    public string NameIngredient { get; set; }
    public string Brand { get; set; }
    public string LBName { get { return NameIngredient + " - " + Brand;}}
    public string RecipeDetail { get; set; }
    public string Parameter { get; set; }
    public string RangeDetail { get; set; }
    public string RangeValue { get; set; }
}

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    RecipeVariables selected = (RecipeVariables)comboBoxRecipeDetail.SelectedItem;
    

    comboBoxRecipeDetail.SelectedItem 是一个字符串 - 当您单击组合框时看到的文本。不能转换为RecipeVariables

    将您的代码更改为:

    using (var db = new GelatoProjectDBEntities())
    {
        RecipeVariables selected = new RecipeVariables()
                                   {
                                       RecipeDetail = (string)comboBoxRecipeDetail.SelectedItem
                                   };
    
        // var results = ...
    }
    

    这将创建一个新的 RecipeVariables 对象,然后将其 RecipeDetail 属性设置为所选组合框项的文本。

    【讨论】:

    • 感谢 Tadija 的回复!我将使用 RecipeVariables 代码编辑主代码。
    • 我编辑了代码。 RangeValue = x.value.ToString() 也可能是您的下一个问题
    • 无法将类型“对象”隐式转换为“字符串”。存在显式转换(您是否缺少演员表?)
    • 现在我在 x.value.ToString() 问题...附加信息:LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且此方法不能翻译成商店表达式。
    • 这是一个不相关的问题,请打开另一个问题,以便我也可以回答。顺便说一句,这是否解决了您当前的问题?
    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2017-11-24
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多