简体   繁体   中英

Is it possible to force an auto-property to use a readonly backing field?

My project contains a large number of classes with properties whose backing field is marked readonly as they are only set at construction. As a matter of style, I like using auto-properties as it eliminates a lot of boilerplate code and encourages use of the property member rather than the backing field. However, when using an auto-property I lose the "readonly-ness" of my backing field. I understand the compiler/runtime is able to take advantage of some performance enhancements when a field is marked this way, so I would like to be able to mark my auto-property as readonly, something like this:

[ReadOnly]
public string LastName { get; }

rather than

private readonly string _LastName;
public string LastName 
{ 
    get
    { 
        return _LastName;
    }
}

Is there some mechanism already available to do this? If not, is the performance gain from the custom backing field being readonly really worthwhile?

Exposing the field as public is another option, I suppose, it just seems wrong to expose a field that way. ie

public readonly string LastName;

I'm afraid not, but you can do this:

public string LastName { get; private set; }

Not quite as good as readonly , but not too bad.

No, unfortunately there's no way of doing this. Personally there are two things that I think are missing from automatically implemented properties in C# - a default value (which I believe will be in VB10) and readonly properties which can only be set in the constructor. In other words, I'd like to be able to do:

public class Foo
{
    public string Tag { get; internal set; } = "Default value";

    // The "readonly" would imply "private" as it could only
    // be set from a constructor in the same class
    public int Value { get; readonly set; }

    public Foo()
    {
        // Valid to set property here, but nowhere else
        Value = 20;
    }
}

As Jared mentioned, this would mean changing compiler calls to the property setter into simple field assignments, and making sure they only occurred in the constructor.

This would make writing immutable types simpler. Unfortunately the situation won't improve in C# 4. Let's hope we get something like this for C# 5...

No it is not and if it was the feature would be useless without significant tweaking.

A readonly field can only be verifiably set from a constructor. A auto-implemented property can only be set from the generated setter. These are incompatible requirements and will produce unverifiable code.

Yes you could potentially make the compiler smart enough to ignore the setter and go straight to the backing field in the constructor. But in the setter itself would still be unverifiable. The compiler would need to omit it from the generated code as will producing a truly read-only property. This produces another contradiction because you would still need to do an assignment statement against the property.

Foo() {
  SomeProperty = "somevalue";
}

In this case the code looks like it's calling a setter on a property. But there is actually no setter to be called since it must be omitted from the final code.

EDIT

This is not saying it can't be done. It can but it would require a bit of work from C#.

In particular they would have to provide a way to set the backing field of a property which cannot have a setter. There are several ways this could be done.

  • Give users access to the backing field of an auto-implemented property
  • Allow the setter style syntax even though there is no setter and let the compiler translate it to a field access under the hood
  • Invent some new syntax

I'm not saying any of these are good options, just possibilities to make this type of feature work .

As of C# 6.0 the answer is yes. Your example can be written as below, and the compiler automatically generates a read-only field behind the property. This is called a getter-only auto-property.

public string LastName { get; }

From https://msdn.microsoft.com/en-us/magazine/dn879355.aspx

Getter-only auto-properties are available in both structs and class declarations, but they're especially important to structs because of the best practice guideline that structs be immutable. Rather than the six or so lines needed to declare a read-only property and initialize it prior to C# 6.0, now a single-line declaration and the assignment from within the constructor are all that's needed. Thus, declaration of immutable structs is now not only the correct programming pattern for structs, but also the simpler pattern—a much appreciated change from prior syntax where coding correctly required more effort.

我更喜欢真正的readonly后备字段,因为这可以保证我在构建后不会更改后备字段。

No and no. There's no way to do this and there's no performance gain to readonly backing fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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