例如我为WP7做计算器。
这是我简单的逻辑类:
public class CalcLogic
{
public static double Calculate(double a, double b, string operation)
{
double res = 0;
switch (operation)
{
case ("+"):
res = a + b;
break;
case ("-"):
res = a - b;
break;
case ("*"):
res = a * b;
break;
case ("/"):
res = a / b;
break;
default: break;
}
return res;
}
}
这是在我的MainPage.xaml.cs:
private const int Rows = 4, Cols = 4;
private string[,] buttonTags = { { "7", "8", "9", "/" },
{ "4", "5", "6", "*" },
{ "1", "2", "3", "-" },
{ "0", "C", "=", "+" }
};
private Button[,] buttons;
// Constructor
public MainPage()
{
InitializeComponent();
CreateButtons();
}
public void CreateButtons()
{
buttons = new Button[Rows, Cols];
for (int i = 0; i < Rows; i++)
{
for (int j = 0; j < Cols; j++)
{
buttons[i, j] = new Button();
buttons[i, j].Content = buttonTags[j, i];
buttons[i, j].Width = 120;
buttons[i, j].Height = 110;
buttons[i, j].Margin = new Thickness(i * 110 + 5, j * 110 + 100, 0, 0);
buttons[i, j].VerticalAlignment = System.Windows.VerticalAlignment.Top;
buttons[i, j].HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
buttons[i, j].Name = "button" + buttonTags[j, i];
buttons[i, j].Click += new System.Windows.RoutedEventHandler(Button_Click);
ContentPanel.Children.Add(buttons[i, j]);
ContentPanel.UpdateLayout();
}
}
}
问题是 - Button_Click方法有多正确?
private void Button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
tbResult.Text += button.Content.ToString();
string operation = "";
double a = 0;
double b = 0;
if (button.Content.ToString() == "=")
{
tbResult.Text = CalcLogic.Calculate(a, b, operation).ToString();
}
if (button.Content.ToString() == "C")
{
tbResult.Text = "";
}
...
}
也许我应该写我的TextBox数字和签名并在解析之后?但我认为这不是正确的算法。
UPD:
这就是我所做的,它运作良好。但我不确定正确的实现:
private void Button_Click(object sender, EventArgs e)
{
try
{
Button button = sender as Button;
double res;
if (Double.TryParse(button.Content.ToString(), out res))
{
DigitClick(button.Content.ToString());
}
else
{
OperatorClick(button.Content.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
ClearAll();
}
}
private void ClearAll()
{
first = second = result = 0;
operStr = "";
newNum = true;
tbResult.Text = "";
}
private void DigitClick(string dig)
{
if (newNum)
{
tbResult.Text = "";
}
tbResult.Text += dig;
newNum = false;
}
private void OperatorClick(string oper)
{
if (oper == "=")
{
if (operStr == "=" || operStr == "")
{
return;
}
second = Convert.ToInt32(tbResult.Text);
result = CalcLogic.Calculate(first, second, operStr);
tbResult.Text = result.ToString();
operStr = oper;
}
else if (oper == "C")
{
ClearAll();
}
else
{
operStr = oper;
first = Convert.ToInt32(tbResult.Text);
}
newNum = true;
}
我只想知道GUI计算器的最佳实现,谢谢。
答案 0 :(得分:0)
不太确定你在问什么,但你永远不会为你的操作变量分配任何东西。它总是一个空字符串。