构造函数和属性初始化
属性值的赋值应该在类的构造函数之前还是之后执行?
public class TestClass
{
public int TestProperty { get; set; } = 2;
public TestClass()
{
if (TestProperty == 1)
{
Console.WriteLine("Shall this be executed?");
}
if (TestProperty == 2)
{
Console.WriteLine("Or shall this be executed");
}
}
}
var testInstance = new TestClass() { TestProperty = 1 };
在上面的示例中, TestProperty
值在类的构造函数中或在类构造函数之后是1
吗?
在实例创建中分配属性值,如下所示:
var testInstance = new TestClass() {TestProperty = 1};
将在构造函数运行后执行。但是,在C#6.0的类'属性中初始化属性值,如下所示:
public class TestClass
{
public int TestProperty { get; set; } = 2;
public TestClass()
{
}
}
将在构造函数运行之前完成。
将上述两个概念结合在一个示例中:
public class TestClass
{
public int TestProperty { get; set; } = 2;
public TestClass()
{
if (TestProperty == 1)
{
Console.WriteLine("Shall this be executed?");
}
if (TestProperty == 2)
{
Console.WriteLine("Or shall this be executed");
}
}
}
static void Main(string[] args)
{
var testInstance = new TestClass() { TestProperty = 1 };
Console.WriteLine(testInstance.TestProperty); //resulting in 1
}
最后结果:
"Or shall this be executed"
"1"
说明:
首先将TestProperty
值指定为2
,然后运行TestClass
构造函数,从而打印出
"Or shall this be executed"
然后由于new TestClass() { TestProperty = 1 }
, TestProperty
将被指定为1
,使得Console.WriteLine(testInstance.TestProperty)
打印的TestProperty
的最终值为
"1"
转 https://riptutorial.com/zh-CN/csharp/example/18800/%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%92%8C%E5%B1%9E%E6%80%A7%E5%88%9D%E5%A7%8B%E5%8C%96
标签:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)