1.默认的无参方式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoInit
{
public class Curry
{
public string MainIngredient { get; set; }
public string Style { get; set; }
public int Spiciness { get; set; }
}
class Program
{
static void Main(string[] args)
{
Curry tastyCurry = new Curry();
// 默认无参的方式初始化
tastyCurry.MainIngredient = "A";
tastyCurry.Style = "B";
tastyCurry.Spiciness = 8;
Console.WriteLine("Hello,{0}",tastyCurry.Style);
Console.ReadKey();
}
}
}
2.定义一个构造函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoInit
{
public class Curry
{
public string MainIngredient { get; set; }
public string Style { get; set; }
public int Spiciness { get; set; }
public Curry (string MainIngredient,string Style,int Spiciness)
{
this.MainIngredient = MainIngredient;
this.Style = Style;
this.Spiciness = Spiciness;
}
}
class Program
{
static void Main(string[] args)
{
// 有参数的构造函数
Curry tastyCurry = new Curry("A","B",8);
Console.WriteLine("Hello,{0}",tastyCurry.Style);
Console.ReadKey();
}
}
}
3.使用对象初始化器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoInit
{
public class Curry
{
public string MainIngredient { get; set; }
public string Style { get; set; }
public int Spiciness { get; set; }
}
class Program
{
static void Main(string[] args)
{
Curry tastyCurry = new Curry
{
MainIngredient = "A",
Style = "B",
Spiciness = 8
};
Console.WriteLine("Hello,{0}",tastyCurry.Style);
Console.ReadKey();
}
}
}
对象初始化器更具有灵活性。
4.进一步结合集合进行处理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoInit
{
public class Curry
{
public string MainIngredient { get; set; }
public string Style { get; set; }
public int Spiciness { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Curry> moreCurries = new List<Curry>
{
new Curry
{
MainIngredient = "A",
Style = "B",
Spiciness = 1
},
new Curry
{
MainIngredient = "C",
Style = "D",
Spiciness = 2
},
new Curry
{
MainIngredient = "E",
Style = "F",
Spiciness = 3
},
};
foreach (Curry myCurry in moreCurries)
{
Console.WriteLine("Hello,{0}", myCurry.Style);
}
Console.ReadKey();
}
}
}
本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6803195.html,如需转载请自行联系原作者