结构和类中字段的初始化以及用new来操作他们的构造函数
生活随笔
收集整理的這篇文章主要介紹了
结构和类中字段的初始化以及用new来操作他们的构造函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
//在下面的示例中,通過使用 new 運(yùn)算符創(chuàng)建并初始化一個(gè) struct 對(duì)象和一個(gè)類對(duì)象,然后為它們賦值。顯示了默認(rèn)值和所賦的值。 using System;
struct SampleStruct
{
??? public int x;
??? public int y;
??? public SampleStruct(int x, int y)
??? {
??????? this.x = x;
??????? this.y = y;
??? }
} class SampleClass
{
??? public string name;
??? public int id; public SampleClass()
??? {
??? } public SampleClass(int id, string name)
??? {
??????? this.id = id;
??????? this.name = name;
??? }
} class MainClass
{
??? static void Main()
??? {
??????? // Create objects using default constructors:
??????? SampleStruct Location1 = new SampleStruct();
??????? SampleClass Employee1 = new SampleClass(); // Display values:
??????? Console.WriteLine("Default values:");
??????? Console.WriteLine("?? Struct members: {0}, {1}",
???????????????? Location1.x, Location1.y);
??????? Console.WriteLine("?? Class members: {0}, {1}",
???????????????? Employee1.name, Employee1.id); // Create objects using parameterized constructors:
??????? SampleStruct Location2 = new SampleStruct(10, 20);
??????? SampleClass Employee2 = new SampleClass(1234, "John Martin Smith"); // Display values:
??????? Console.WriteLine("Assigned values:");
??????? Console.WriteLine("?? Struct members: {0}, {1}",
???????????????? Location2.x, Location2.y);
??????? Console.WriteLine("?? Class members: {0}, {1}",
???????????????? Employee2.name, Employee2.id);
??? }
}
struct SampleStruct
{
??? public int x;
??? public int y;
??? public SampleStruct(int x, int y)
??? {
??????? this.x = x;
??????? this.y = y;
??? }
} class SampleClass
{
??? public string name;
??? public int id; public SampleClass()
??? {
??? } public SampleClass(int id, string name)
??? {
??????? this.id = id;
??????? this.name = name;
??? }
} class MainClass
{
??? static void Main()
??? {
??????? // Create objects using default constructors:
??????? SampleStruct Location1 = new SampleStruct();
??????? SampleClass Employee1 = new SampleClass(); // Display values:
??????? Console.WriteLine("Default values:");
??????? Console.WriteLine("?? Struct members: {0}, {1}",
???????????????? Location1.x, Location1.y);
??????? Console.WriteLine("?? Class members: {0}, {1}",
???????????????? Employee1.name, Employee1.id); // Create objects using parameterized constructors:
??????? SampleStruct Location2 = new SampleStruct(10, 20);
??????? SampleClass Employee2 = new SampleClass(1234, "John Martin Smith"); // Display values:
??????? Console.WriteLine("Assigned values:");
??????? Console.WriteLine("?? Struct members: {0}, {1}",
???????????????? Location2.x, Location2.y);
??????? Console.WriteLine("?? Class members: {0}, {1}",
???????????????? Employee2.name, Employee2.id);
??? }
}
總結(jié)
以上是生活随笔為你收集整理的结构和类中字段的初始化以及用new来操作他们的构造函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Rails Migrations
- 下一篇: 菜鸟成长日记(四)之WMIC简单命令应用