Set properties of a class only through constructor

2019-02-08 03:01发布

I am trying to make the properties of class which can only be set through the constructor of the same class.

4条回答
一夜七次
2楼-- · 2019-02-08 03:39

Make the properties have readonly backing fields:

public class Thing
{
   private readonly string _value;

   public Thing(string value)
   {
      _value = value;
   }

   public string Value { get { return _value; } }
}
查看更多
Anthone
3楼-- · 2019-02-08 03:53

As of c# 6.0 you now can have get only properties that can be set in the constructor (even though there is no set defined in the property itself. See Property with private setter versus get-only-property

查看更多
对你真心纯属浪费
4楼-- · 2019-02-08 03:55

This page from Microsoft describes how to achieve setting a property only from the constructor.

You can make an immutable property in two ways. You can declare the set accessor.to be private. The property is only settable within the type, but it is immutable to consumers. You can instead declare only the get accessor, which makes the property immutable everywhere except in the type’s constructor.

In C# 6.0 included with Visual Studio 2015, there has been a change that allows setting of get only properties from the constructor. And only from the constructor.

The code could therefore be simplified to just a get only property:

public class Thing
{
   public Thing(string value)
   {
      Value = value;
   }

   public string Value { get; }
}
查看更多
We Are One
5楼-- · 2019-02-08 03:55

The correct way is:

public string MyProperty{ get; private set; }

public MyClassConstructor(string myProperty)
{
     MyProperty= myProperty;
}
查看更多
登录 后发表回答