什么时候应该使用只读并获得唯一性什么时候、唯一性

2023-09-03 08:41:40 作者:阳光照进回忆里

在.NET应用程序时,应该使用只读属性,当我应该只使用获取。是什么这两者之间的区别。

 私人只读双燃料= 0;

大众双FuelConsumption
         {
            得到
            {
               回油;
            }
         }
 

 专用双燃料= 0;

大众双FuelConsumption
         {
                得到
                {
                   回油;
                }
             }
 
文件属性中的只读和隐藏表示什么意思啊

解决方案

创建只有一个getter属性,使你的属性只读任何code,它是类之外。

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

 公共类FuelConsumption {
    私人双燃料;
    大众双燃料
    {
        {返回this.fuel; }
    }
    公共无效FillFuelTank(双量)
    {
        this.fuel + =量;
    }
}

公共静态无效的主要()
{
    FuelConsumption F =新FuelConsumption();

    双A;
    A = f.Fuel; // 将工作
    f.Fuel =一个; //不能编译

    f.FillFuelTank(10); //值从方法的code改
}
 

设置你的类的私有字段为只读允许您设置字段值只有一次(使用内联转让或在类的构造函数)。 你会不会在以后改变它。

 公共类ReadOnlyFields {
    私人只读双A = 2.0;
    私人只读双B:

    公共ReadOnlyFields()
    {
        this.b = 4.0;
    }
}
 

只读类字段通常用于那些类敷设渠道的过程中初始化的变量,并且永远不会在日后发生变化。

总之,如果你需要确保你的属性值将永远不会从外部改变,但是您需要能够把它从你的类code更改,请使用的Get-只有属性。

如果你需要存储值永远不会改变,一旦它的初始值已设置,使用只读字段。

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

private readonly double Fuel= 0;

public double FuelConsumption
         {
            get
            {
               return Fuel;
            }
         }

or

private double Fuel= 0;

public double FuelConsumption
         {
                get
                {
                   return Fuel;
                }
             }

解决方案

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

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.

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 contruction, and will never changed later on.

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

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