简体   繁体   English

自动属性无法在C#实例构造函数中初始化

[英]Automatic properties fail to initialize in C# instance constructor

I need a sanity check to determine whether my C# compiler is broken or I'm not understanding how automatic properties are supposed to work. 我需要进行完整性检查,以确定我的C#编译器是否损坏,或者我不了解自动属性应如何工作。

Given the following class definition and constructor, note the respective member values. 给定以下类定义和构造函数,请注意各自的成员值。

public class MyClass
{
    public string MyString { get; set; }
    public string _anotherString;

    public MyClass()
    {
        MyString = "some value";
        // <--- debugger shows MyString as null

        _anotherString = "another value";
        // <--- debugger shows _anotherString as "another value"
    }
}

This continues to happen with a variety of classes. 这在各种类中继续发生。 In short, all automatic properties fail to initialize when assigning values in the constructor. 简而言之,在构造函数中分配值时,所有自动属性均无法初始化。 They work everywhere else. 他们在其他地方工作。 However, if I change them to use backing stores and initialize the backing variable, they are initialized properly. 但是,如果我更改它们以使用后备存储并初始化后备变量,则它们将正确初始化。

Am I correct in assuming that it is always safe to initialize automatic properties in the constructor, or am I missing something? 我是否假设在构造函数中初始化自动属性总是安全的,还是我遗漏了某些东西? And if it is, then what could be going on with Visual Studio? 如果是的话,那么Visual Studio会发生什么?

Have you tried with a fresh new project? 您是否尝试过一个新的新项目? Did you CLEAN the solution (Build > Clean Solution), close all opened documents/tabs and then do a rebuild (not a build, rebuild!) and try again? 您是否清洁了解决方案(“构建”>“清洁解决方案”),关闭了所有打开的文档/选项卡,然后进行了重建(不是重建,而是重建!),然后重试?

I determined that this was caused by a conflict between two PostSharp aspect attributes. 我确定这是由两个PostSharp方面属性之间的冲突引起的。 Not a problem with PostSharp, but with a custom attribute I had created to intercept property assignments. PostSharp没问题,但是我创建了一个自定义属性来拦截属性分配。 Removing the extra attribute allowed it to work normally. 删除多余的属性可以使其正常工作。

Essentially, when there are multiple aspects applied to the same object, PostSharp does some tricky maneuvers when "weaving" the generated code. 本质上,当有多个方面应用于同一对象时,PostSharp在“编织”生成的代码时会进行一些棘手的操作。 Still trying to determine how to fix it, but at least I'm not going completely insane. 仍在尝试确定如何修复它,但至少我并没有完全发疯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM