c# - 构造函数初始化优化?

标签 c# constructor initialization

注意:我在这里使用 .NET 3.5。

假设我有具有以下构造函数的示例基类/子类:

public Person(string name, int age, string job, bool isMale)
{  
    Name = name;
    Age = age;
    Job = job;
    IsMale = isMale;
}  

public CollegeStudent(string name) : this(name, 18) {}

public CollegeStudent(string name, int age) : this(name, age, "Student") {}

public CollegeStudent(string name, int age, string job) : this(name, age, job, true) {}

public CollegeStudent(string name, int age, string job, bool isMale) : base(name, age, job, isMale) {}

编译器是否足够聪明,可以看出子构造函数所做的唯一事情就是相互链接并最终调用基构造函数?那么,它可以只更改“this”构造函数初始值设定项以在编译时直接调用基本构造函数吗?

所以它会在本质上改变一切:

public CollegeStudent(string name) : base(name, 18, "Student", true) {}

public CollegeStudent(string name, int age) : base(name, age, "Student", true) {}

public CollegeStudent(string name, int age, string job) : base(name, age, job, true) {}

public CollegeStudent(string name, int age, string job, bool isMale) : base(name, age, job, isMale) {}

我想像第一部分一样编写我的构造函数,因为它很方便,但如果我只是想招致无用的开销,我可能会直接为每个构造函数调用基本构造函数。

最佳答案

C# 编译器将沿着链式构造函数行向后走,直到它到达 Object 的构造函数。当您使用链式构造函数时,我认为没有太多需要优化的地方。要自己找出答案,您可以尝试编译该代码,然后使用 Reflector查看优化后的代码。

在那之前,我等待 Jon Skeet。

编辑

我只是将这个简单的代码编译成一个类(.Net 3.5):

namespace Person {
    public class Person {
        private String Name;
        private int Age;
        private String Job;
        private Boolean IsMale;

        public Person(string name, int age, string job, bool isMale) {
            Name = name;
            Age = age;
            Job = job;
            IsMale = isMale;
        }
    }

    public class CollegeStudent : Person {
        public CollegeStudent(string name) : this(name, 18) { }
        public CollegeStudent(string name, int age) : this(name, age, "Student") { }
        public CollegeStudent(string name, int age, string job) : this(name, age, job, true) { }
        public CollegeStudent(string name, int age, string job, bool isMale) : base(name, age, job, isMale) { }
    }
}

使用 Reflector,我发现 C# 编译器没有按照您建议的方式优化任何构造函数。

关于c# - 构造函数初始化优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5052514/

相关文章:

c# - 运行一个字符串作为构建电子邮件的指令

c# - 使用 GuidRepresentation.Standard GuidSerializer 执行查询时 MongoDB C# 驱动程序出现问题

C++:类 - 重载构造函数 - 单变量?

c++ - 是否可以在类中构造类?

c# - 我可以获取 .ascx 文件以在类库中编译吗?

c# - 从 ASP.NET CORE 中的字节加载程序集

c++ - 在具有继承的模板中复制构造函数和赋值运算符

c++ - 基类需要引用尚未构造的派生类成员

swift - 自动初始化器继承的条件是初始化器的签名

c++ - C++中"int"和"const int"的初始化和转换