如何创建新类型的变量(如 C#.net 中的 Button)

How to create new type of variables (like Button in c#.net)

所以这个问题我想了很久,但是所有的想法都落空了。

例如,当您创建一个新的 windows 应用程序并在您的表单中放置一个按钮时,您将创建一个按钮单击事件,然后它会发生:

您有 (object sender) 和 (EventArgs e)

然后你像这样投射它:Button button = (Button)sender;

现在:我如何创建像 "Button" 这样的东西,例如我想创建一个名为 "Book" 的新类型,然后键入:"Book myBook = new Book();"

即使没有深入的 C# 知识,这也可能吗?

您可以阅读有关 classes 的更多信息。我认为您真正想知道的是如何创建 class。

这是一个 class 的例子:

public class Book
{
   public string Title {get;set;}
   public string Author {get;set;}
}

以下是您的使用方法。

Book book1 = new Book(); 
book1.Title = "Harry Potter";
book1.Author = "J.K. Rowling";
Console.WriteLine("{0} by {1}", book1.Title, book1.Author);

这是为 class 创建构造函数的方法。

public class Book
{
   //To create a constructor, you just create a method using the class name. 
   public Book(string title, string author)
   {
      this.Title = title;
      this.Author = author; 
   }

   //Creating a constructor with parameters eliminates the default 
   //constructor that's why you might want to add this if you want to          
   //instantiate the class without a parameters. 
   public Book() { } 

   public string Title {get;set;}
   public string Author {get;set;}
}

使用该构造函数,您可以通过

创建 class 的实例
Book book1 = new Book("Harry Potter", "J.K. Rowling"); 

另一种方法是使用初始值设定项。这样您就不需要传递构造函数参数来填充属性的值。

您可能想阅读此.. https://msdn.microsoft.com/en-us/library/x9afc042.aspx

  Book book1 = new Book() { Title = "Harry Potter", Author = "J.K. Rowling" };

您读过 C# 吗?如果是这样,您应该了解 类 和结构。

class Book
{
  public string ISBN{get;set;}
  public float Price {get;set;}
}

Book myBook = new Book { ISBN="###-####-",Price=22.3}

这里是type和class的区别:
Difference between class and type

关于如何在 c# 中 create/use 一个 class 的好而简单的教程:
http://www.tutorialspoint.com/csharp/csharp_classes.htm

您还可以扩展这些元素,例如 Buttons 或 TextBox 以根据需要构建它:
http://www.c-sharpcorner.com/UploadFile/ehtesham.dotnet/how-to-create-a-custom-control/