简体   繁体   English

您需要一个带有构造函数的只读属性,让您为该属性设置值吗?

[英]What do you need a read-only property with a constructor that let's you set the values in that property for?

How is a read-only property with a constructor that lets you set the values: 具有构造器的只读属性如何使您可以设置值:

public class Customer
{
    private int m_id = -1;

    public Customer(int id)
    {
         m_id = id;
    }

    public int ID
    {
        get
        {
            return m_id;
        }
    }
}

different from a normal get, set property like the following? 与正常的get,set属性不同如下所示?

public class Customer
{
    private int m_id = -1;

    public int ID
    {
        get
        {
            return m_id;
        }
        set
        {
            m_id = value;
        }
    }

The read-only property does not allow other classes within the program to set the property value. read-only property不允许程序中的其他类设置property值。 The traditional property does. 传统property确实如此。

In this case, the class is forcing the programmer to provide an int ID in the constructor. 在这种情况下, class将迫使程序员在构造函数中提供一个int ID Having a public property would nearly negate this requirement as the programmer could alter the value of ID at any time. 拥有public property几乎可以抵消这一要求,因为程序员可以随时更改ID的值。

Members variables set within the object constructor can be declared using the readonly keyword. 可以使用readonly关键字声明在对象构造函数中设置的成员变量。 This allows the variable to act as a constant (eg attempting to change it will generate a compile-time error) but still allow you to set it to a different value for each object instance. 这允许变量充当常量(例如,尝试对其进行更改将生成编译时错误),但仍允许您为每个对象实例将其设置为不同的值。 This is a bit of syntactic sugar that can help prevent your coders from accidentally modifying values that are not meant to be modified. 这是一点语法上的糖,可以帮助防止您的编码人员意外修改不希望修改的值。

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

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