只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句 [英] Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

查看:19
本文介绍了只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 foreach 部分,我试图在result = string.Format"之后添加一行,但出现以下错误只能使用赋值、调用、递增、递减、等待和新对象表达式作为声明"有人可以告诉我我做错了什么.

I have this foreach section and i am trying to add a line after my "result = string.Format" but i get the following error "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement" can someone tell me what i am doing wrong.

foreach (DataRow record in table.Rows)
{
    string key = record["Code"] + "_" + record["Description"];
    int row = (int)rownum[key];

    string date = formatDate(record["ApptDate"].ToString(), "_");

    string result = string.Empty;
    if (record["Dosage"].ToString() != string.Empty)
        result = string.Format("{0}/{1}", test.SharedLib.Application.RemoveTrailingZeroes(record["Dosage"].ToString()), 
                                          test.SharedLib.Application.RemoveTrailingZeroes(record["Units"].ToString()));
    if (record["Dosage"].ToString() != string.Empty)
        result.StartsWith("/") && result.EndsWith("/") ? result.Replace("/", string.Empty) : result;
    else if (record["Units"].ToString() != string.Empty)
        result = record["Units"].ToString();

    dataTable.Rows[row]["ApptDate" + date] = result;
}

推荐答案

if (record["Dosage"].ToString() != string.Empty)
    result.StartsWith("/") && result.EndsWith("/") ? result.Replace("/", string.Empty) : result;

第二行不是语句,是表达式.不是所有的表达式都可以是 C# 中的语句,所以这是一个语法错误.

The second line there is not a statement, it is an expression. Not all expressions can be statements in C#, so this is a syntax error.

大概你打算将这个结果分配给 result:

Presumably you meant to assign the result of this to result:

if (record["Dosage"].ToString() != string.Empty)
    result = (result.StartsWith("/") && result.EndsWith("/")) ? result.Replace("/", string.Empty) : result;

此外,您应该考虑用大括号 ({}) 将 if/else 块的主体括起来.如果没有大括号,这些块的嵌套方式不直观,并且会妨碍未来的维护.(例如,你能分辨出 else if 块属于哪个 if 块吗?下一个继承这个项目的人不仅能分辨出区别,而且了解什么是嵌套意图?明确表示!)

Further, you should consider enclosing the bodies of if / else blocks with braces ({}). Without braces, the way in which these blocks nest is not intuitive, and it will hamper future maintenance. (For example, can you tell which if block the else if block will belong to? Will the next person who inherits this project be able to not only tell the difference, but understand what nesting was intended? Make it explicit!)

这篇关于只有赋值、调用、递增、递减、等待和新对象表达式可以用作语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆