首页 > 解决方案 > 为什么 char.Equals() 方法不适用于“.”、“+”、“-”、“/”或“*”

问题描述

我正在尝试使用 WPF 在 C# 中构建一个计算器,我需要知道显示器(System.Windows.Controls.TextBlock 对象)中是否有一些运算符,如 +、-、/ 或 *。

我命名为“Display”的 TextBlock:

<TextBlock Name="Display" Text="0" FontFamily="Consolas" FontSize="60" 
           HorizontalAlignment="Right" VerticalAlignment="Bottom" 
           Padding="15" Height="120"></TextBlock>

当我调用 TextBlock.Text(返回一个字符串)属性并尝试将该字符串(一个字符)的某个索引与另一个字符(.、+、-、/、*)与 char.Equals( ) 方法:

private void Dot_Click(object sender, RoutedEventArgs e)
        {
            if (Display.Text.Length < 20 & !".".Equals(Display.Text[Display.Text.Length - 1])) Display.Text += ".";
        }

我希望当显示中的最后一个字符是一个点时,用户不能写更多的点。像这样:

在此处输入图像描述

但刚刚发生了这样的事情:

在此处输入图像描述

当我输入 +、-、* 或 / 时也会出现同样的问题

感谢您的帮助!

标签: c#.netwpf

解决方案


您应该与 char 进行比较。您正在尝试比较字符串和字符。"."是一个字符串并且'.'是一个字符。

private void Dot_Click(object sender, RoutedEventArgs e)
    {
        if (Display.Text.Length < 20 & !'.'.Equals(Display.Text[Display.Text.Length - 1])) Display.Text += ".";
    }

推荐阅读