什么时候应该使用Readonly并获得属性?

时间:2021-10-12 13:11:35

In a .NET application when should I use "ReadOnly" properties and when should I use just "Get". What is the difference between these two.

在。net应用程序中,何时应该使用"ReadOnly"属性,何时应该使用"Get"。这两者的区别是什么?

private readonly double Fuel= 0;

public double FuelConsumption
{
    get
    {
        return Fuel;
    }
}        

or

private double Fuel= 0;

public double FuelConsumption
{
     get
     {
          return Fuel;
     }
}

5 个解决方案

#1


94  

Creating a property with only a getter makes your property read-only for any code that is outside the class.

仅使用getter创建属性会使您的属性对类之外的任何代码都是只读的。

You can however change the value using methods provided by your class :

不过,您可以使用类提供的方法更改值:

public class FuelConsumption {
    private double fuel;
    public double Fuel
    {
        get { return this.fuel; }
    }
    public void FillFuelTank(double amount)
    {
        this.fuel += amount;
    }
}

public static void Main()
{
    FuelConsumption f = new FuelConsumption();

    double a;
    a = f.Fuel; // Will work
    f.Fuel = a; // Does not compile

    f.FillFuelTank(10); // Value is changed from the method's code
}

Setting the private field of your class as readonly allows you to set the field value only once (using an inline assignment or in the class constructor). You will not be able to change it later.

将类的私有字段设置为readonly允许您只设置一次字段值(使用内联赋值或类构造函数)。以后你将无法更改它。

public class ReadOnlyFields {
    private readonly double a = 2.0;
    private readonly double b;

    public ReadOnlyFields()
    {
        this.b = 4.0;
    }
}

readonly class fields are often used for variables that are initialized during class construction, and will never be changed later on.

readonly类字段通常用于在类构造期间初始化的变量,并且以后永远不会更改。

In short, if you need to ensure your property value will never be changed from the outside, but you need to be able to change it from inside your class code, use a "Get-only" property.

简而言之,如果您需要确保您的属性值不会从外部更改,但是您需要能够从类代码内部更改它,请使用“Get-only”属性。

If you need to store a value which will never change once its initial value has been set, use a readonly field.

如果您需要存储一个值,一旦它的初始值被设置,它将不会改变,使用readonly字段。

#2


6  

A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).

只有getter的属性称为只读属性。因为没有提供任何setter来更改属性的值(从外部)。

C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).

c#有一个关键字readonly,可以用于字段(而不是属性)。被标记为“readonly”的字段,只能在对象构造期间(在构造函数中)设置一次。

private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;

public string Name{ // This is a readonly property.
  get {
    return _name;  
  }
}

public bool Enabled{ // This is a read- and writeable property.
  get{
    return _enabled;
  }
  set{
    _enabled = value;
  }
} 

#3


3  

As of C# 6 you can declare and initialise a 'read-only auto-property' in one line:

从c# 6开始,您可以在一行中声明和初始化一个“只读自动属性”:

double FuelConsumption { get; } = 2;

You can set the value from the constructor but not other methods.

可以从构造函数中设置值,但不能从其他方法中设置。

#4


1  

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

只读属性用于创建故障安全代码。我非常喜欢Mark Seemann关于属性和支持字段的封装post系列:

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

taken from Mark's example:

从马克的例子:

public class Fragrance : IFragrance
{
    private readonly string name;

    public Fragrance(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this.name = name;
    }

    public string Spread()
    {
        return this.name;
    }
}

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

在本例中,您使用readonly名称字段来确保类不变量始终有效。在这种情况下,类编写器希望确保name字段只设置一次(不可变的),并且始终存在。

#5


0  

Methods suggest something has to happen to return the value, properties suggest that the value is already there. This is a rule of thumb, sometimes you might want a property that does a little work (i.e. Count), but generally it's a useful way to decide.

方法表明必须发生一些事情来返回值,属性表明值已经存在。这是一个经验法则,有时你可能想要一个做一些工作的属性(比如计数),但是通常它是一个有用的决定方法。

#1


94  

Creating a property with only a getter makes your property read-only for any code that is outside the class.

仅使用getter创建属性会使您的属性对类之外的任何代码都是只读的。

You can however change the value using methods provided by your class :

不过,您可以使用类提供的方法更改值:

public class FuelConsumption {
    private double fuel;
    public double Fuel
    {
        get { return this.fuel; }
    }
    public void FillFuelTank(double amount)
    {
        this.fuel += amount;
    }
}

public static void Main()
{
    FuelConsumption f = new FuelConsumption();

    double a;
    a = f.Fuel; // Will work
    f.Fuel = a; // Does not compile

    f.FillFuelTank(10); // Value is changed from the method's code
}

Setting the private field of your class as readonly allows you to set the field value only once (using an inline assignment or in the class constructor). You will not be able to change it later.

将类的私有字段设置为readonly允许您只设置一次字段值(使用内联赋值或类构造函数)。以后你将无法更改它。

public class ReadOnlyFields {
    private readonly double a = 2.0;
    private readonly double b;

    public ReadOnlyFields()
    {
        this.b = 4.0;
    }
}

readonly class fields are often used for variables that are initialized during class construction, and will never be changed later on.

readonly类字段通常用于在类构造期间初始化的变量,并且以后永远不会更改。

In short, if you need to ensure your property value will never be changed from the outside, but you need to be able to change it from inside your class code, use a "Get-only" property.

简而言之,如果您需要确保您的属性值不会从外部更改,但是您需要能够从类代码内部更改它,请使用“Get-only”属性。

If you need to store a value which will never change once its initial value has been set, use a readonly field.

如果您需要存储一个值,一旦它的初始值被设置,它将不会改变,使用readonly字段。

#2


6  

A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).

只有getter的属性称为只读属性。因为没有提供任何setter来更改属性的值(从外部)。

C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).

c#有一个关键字readonly,可以用于字段(而不是属性)。被标记为“readonly”的字段,只能在对象构造期间(在构造函数中)设置一次。

private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;

public string Name{ // This is a readonly property.
  get {
    return _name;  
  }
}

public bool Enabled{ // This is a read- and writeable property.
  get{
    return _enabled;
  }
  set{
    _enabled = value;
  }
} 

#3


3  

As of C# 6 you can declare and initialise a 'read-only auto-property' in one line:

从c# 6开始,您可以在一行中声明和初始化一个“只读自动属性”:

double FuelConsumption { get; } = 2;

You can set the value from the constructor but not other methods.

可以从构造函数中设置值,但不能从其他方法中设置。

#4


1  

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

只读属性用于创建故障安全代码。我非常喜欢Mark Seemann关于属性和支持字段的封装post系列:

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

taken from Mark's example:

从马克的例子:

public class Fragrance : IFragrance
{
    private readonly string name;

    public Fragrance(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this.name = name;
    }

    public string Spread()
    {
        return this.name;
    }
}

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

在本例中,您使用readonly名称字段来确保类不变量始终有效。在这种情况下,类编写器希望确保name字段只设置一次(不可变的),并且始终存在。

#5


0  

Methods suggest something has to happen to return the value, properties suggest that the value is already there. This is a rule of thumb, sometimes you might want a property that does a little work (i.e. Count), but generally it's a useful way to decide.

方法表明必须发生一些事情来返回值,属性表明值已经存在。这是一个经验法则,有时你可能想要一个做一些工作的属性(比如计数),但是通常它是一个有用的决定方法。