首页 > 解决方案 > 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#wpf

解决方案


所有 C# 程序都需要一个static Main方法作为入口点。MainWindow是一个类,而不是一个入口点。


推荐阅读