c# - WPF 应用程序中是否需要 Main()?
问题描述
我对 .NET 完全陌生,我正在尝试通过运行我在遵循的书中遇到的代码来了解 C#。
我正在构建一个带有按钮的简单 WPF 应用程序,它应该打印出斜边。我的问题是;在本书的下面代码示例中,有这两个命名空间(Syncfusion 和 NamespaceDemo)。我必须将它们都包括在内吗?使用这些代码的更好方法是什么?其次,当为应用程序创建一个新的 WPF 文件和一个按钮时,它会自动生成这段代码:
public MainWindow()
{
InitializeComponent();
}
我知道 MainWindow() 用于包含按钮的设计。它与简单 C# 控制台应用程序中的 Main() 函数有何不同?我希望能清楚地解释我对如何正确构建这些不同的事物的困惑。我需要一个 Main() 吗?
这是书中的代码:
using static System.Math;
namespace Syncfusion
{
public class Calc
{
public static double Pythagorean(double a, double b)
{ double cSquared = Pow(a, 2) + Pow(b, 2);
return Sqrt(cSquared); }
}
}
using Syncfusion;
using System;
using Crypto = System.Security.Cryptography;
namespace NamespaceDemo
{
class Program
{
static void Main()
{
double hypotenuse = Calc.Pythagorean(2, 3);
Console.WriteLine("Hypotenuse: " + hypotenuse);
Crypto.AesManaged aes = new Crypto.AesManaged();
Console.ReadKey();
}
}
}
这是我的实现,不幸的是它不起作用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Math;
namespace Syncfusion
{
public class Calc
{
public static double Pythagorean(double a, double b)
{
double cSquared = Pow(a, 2) + Pow(b, 3);
return Sqrt(cSquared);
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void Button_Click(object sender, RoutedEventArgs e)
{
double hypotenuse = Calc.Pythagorean(2, 4);
MessageBox.Show("Hypotenuse: " + hypotenuse);
}
}
}
解决方案
所有 C# 程序都需要一个static
Main
方法作为入口点。MainWindow
是一个类,而不是一个入口点。
推荐阅读
- scala - 在 Spark SQL 窗口中查找和标记最大行
- amp-html - Google AMP Story Analytics,使用 Segment
- c# - 在 WPF C# 应用程序中保存 rpt 文件时出错
- gnuplot - 使用 gnuplot 更改条形图上的条形颜色
- emacs - 根据文件扩展名设置emacs注释样式
- rally - 使用 wsapi.Store 显示所有关联的子项
- android - 设置 TabLayout 背景透明
- javascript - 如何将类名添加到特定元素
- c# - 循环遍历 Json 文件并提取特定数据
- r - 与其他绘图(ggplot2)结合时如何将geom_bar中的计数更改为百分比?