简体   繁体   English

如何通过调用构造函数来提供只读属性的值?

[英]How can I supply a read-only property's value by calling a constructor?

I have a Book class with a constructor which has a title parameter:我有一本书 class 带有一个具有标题参数的构造函数:

public class Book
    public Book (string title)
        {
           this.Title = title;
        }

I need to supply a Title's (read-only property) value by calling the Book constructor.我需要通过调用 Book 构造函数来提供 Title 的(只读属性)值。 I tried the following but not sure if this is correct since as I understood read-only property should only have a getter.我尝试了以下但不确定这是否正确,因为据我了解只读属性应该只有一个吸气剂。

public string Title { get; private set {} }

I need Help to Finalize / correct this code block.我需要帮助来完成/更正此代码块。 Thank you in advance.先感谢您。

As you have currently defined Title , it is able to be set from anywhere inside Book .正如您当前定义的Title ,它可以从Book中的任何位置进行设置。 That is to say, it is not read-only, merely private.也就是说,它不是只读的,只是私有的。

To make it read-only (in a similar way to the readonly keyword on fields) you can simply declare it like this:要使其成为只读(类似于字段上的readonly关键字),您可以简单地声明它,如下所示:

public string Title { get; }

And then you can use the constructor code you currently have to initialize it:然后您可以使用当前必须对其进行初始化的构造函数代码:

public Book (string title)
{
    this.Title = title;
}

As Ran notes in the other answer , C# 9 has introduced the concept of the init modifier .正如 Ran 在另一个答案中指出的那样,C# 9 引入了init修饰符的概念。 The difference with init is that, while the property can still only be set once, it can be initialized from outside the constructor.init的不同之处在于,虽然该属性仍然只能设置一次,但可以从构造函数外部对其进行初始化。 This is useful if you want to use the object initializer pattern, for example.例如,如果您想使用 object 初始化模式,这将非常有用。

C# 9 introduces the init keyword which is a variation of set , which allows us to do it. C# 9 引入了init关键字,它是set的变体,它允许我们这样做。 The init accessor is actually a variant of the set accessor which can only be called during object initialization init访问器实际上是set访问器的变体,只能在 object 初始化期间调用

public class Book
{
    public string Title { get; init }; 
} 

More about init - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init更多关于init - https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init

Any read only field can be set in the constructor, where after the constructing is done the field will become immutable.任何只读字段都可以在构造函数中设置,构造完成后该字段将变为不可变。 In other words, you don't need to do anything fancy, the constructor will handle it.换句话说,你不需要做任何花哨的事情,构造函数会处理它。

Just do an interface with your只需与您的interface

public string Title { get; }

and then implement this interface into your class/classes & do a simple field (outside the constructor, over your method):然后将此接口实现到您的类/类中并做一个简单的field (在构造函数之外,在您的方法上):

public string Title => "xyz"; //(or string.Empty)

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

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