结构和类中字段的初始化以及用new来操作他们的构造函数

//在下面的示例中,通过使用 new 运算符创建并初始化一个 struct 对象和一个类对象,然后为它们赋值。显示了默认值和所赋的值。
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);
    }
}













本文转自terryli51CTO博客,原文链接:http://blog.51cto.com/terryli/519513 ,如需转载请自行联系原作者


上一篇:小项目需要前后端分离吗?


下一篇:Microsoft Surface 设计与开发官方培训