C#的ToString增量 [英] C# increment ToString

查看:152
本文介绍了C#的ToString增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从C#/ WPF添加一个意外的行为。

I add an unexpected behaviour from C#/WPF

    private void ButtonUp_Click(object sender, RoutedEventArgs e)
    {
        int quant;
        if( int.TryParse(Qnt.Text, out quant))
        {
            string s = ((quant++).ToString());
            Qnt.Text = s;
        }
    }



所以,如果我得到定量为1,定量会?递增为2。但S字符串将是1.这是优先级的问题。

So, if I get quant as 1, quant will be incremented to 2. But the s string will be 1. Is this a question of precedence?

编辑:

我重新写了这个为:

            quant++;
            Qnt.Text = quant.ToString();

和现在这个工程,我的预期。

and now this works as I expected.

推荐答案

您正在使用的发布的-Increment运营商。此evalutates到原始值,然后递增。做你想做的事,一个班轮你可以使用的的-Increment操盘手。

You are using the post-increment operator. This evalutates to the original value, and then increments. To do what you want in a one-liner you can use the pre-increment operator instead.

(++quant).ToString();



不过,更妙的是,以避免所有这些缺陷并做到这一点是这样的:

But even better would be to avoid all such pitfalls and do it like this:

quant++;
string s = quant.ToString();

通过你要想想这事情发生的顺序第一个版本。在第二个版本没有想到是必需的。始终值代码清晰度比更高简洁性。

With the first version you have to think about the order in which things happen. In the second version no thought is required. Always value code clarity more highly than conciseness.

这很容易相信一个行版本是有点快,但事实并非如此。它可能在20世纪70年代空调系统在当天已经真正回来,但即使这样,我怀疑。

It's easy to believe that the one-line version is somehow faster, but that's not true. It might have been true back in the day in 1970s C systems, but even then that I doubt.

这篇关于C#的ToString增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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