如下代码示例所示 d1 d2 相等,d3 d4 不等,因为赋值形式的访问器只是new一个实例后赋值,而lambda形式(箭头函数),则是把箭头右侧是当方法体来执行,即每次都 new一个新的实例
class Dog
{
public Dog()
{
this.Name = Guid.NewGuid().ToString("N");
}
public string Name { get; set; }
public DateTime CreateTime { get; set; } = DateTime.Now;
}
class DogHouse
{
public static Dog Dog1 { get; } = new();
public static Dog Dog2 => new();
}
internal class Program
{
static void Main(string[] args)
{
var d1 = DogHouse.Dog1;
var d2 = DogHouse.Dog1;
var d3 = DogHouse.Dog2;
var d4 = DogHouse.Dog2;
var isSame1 = d1 == d2;
var isSame2 = d3 == d4;
Console.WriteLine($"isSame1:{isSame1},isSame2:{isSame2}");
}
}
标签:DogHouse,get,Dog,访问,var,new,public,属性
From: https://www.cnblogs.com/DHclly/p/17824403.html