zoukankan      html  css  js  c++  java
  • 构造函数和属性初始化

    属性值的赋值应该在类的构造函数之前还是之后执行?

    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
  • 相关阅读:
    Java框架介绍-13个不容错过的框架项目
    微信公众号 模板消息开发
    微信授权-授权方式、公众号是否关注
    Java Spring-Spring与Quartz整合
    Java框架搭建-Maven、Mybatis、Spring MVC整合搭建
    IOS UIView 04- 自定义控件
    IOS UIView 03- 自定义 Collection View 布局
    IOS UIView 02- 深入理解 Scroll Views
    MVC架构中的Repository模式 个人理解
    零开始的领域驱动设计
  • 原文地址:https://www.cnblogs.com/wl-blog/p/13841383.html
Copyright © 2011-2022 走看看