Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

c# - Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

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

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.

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;

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!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...