【问题标题】:Is Main() required in a WPF application? [duplicate]WPF 应用程序中是否需要 Main()? [复制]
【发布时间】:2018-12-09 10:52:29
【问题描述】:

我对 .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);
        }
    }
}

【问题讨论】:

  • 如果您不理解某行代码,最好不要使用它。您的表单或数学函数不需要 AES
  • 很好的提示。谢谢。
  • “我的问题是;在本书的下面代码示例中,有这两个命名空间(Syncfusion 和 NamespaceDemo)。我必须同时包含它们吗?”仅当您使用其功能或组件之一时,才需要 Syncfusion。另一个命名空间可能是你的书示例代码。

标签: c# wpf


【解决方案1】:

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

【讨论】:

  • 谢谢。所以我必须将 button_Clicked() 放在 Main() 中?
  • @user9419320 不完全是。看起来您根本不需要 wpf,因为您使用的是Console
  • 我没有使用控制台。我正在尝试wpf。但是书中的代码是用于控制台的。我正在尝试将它用于 wpf。
猜你喜欢
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 2012-11-19
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多