c# - 仅通过构造函数设置类的属性

标签 c# properties constructor set

我正在尝试创建只能通过同一类的构造函数设置的类的属性。

最佳答案

This page from Microsoft描述了如何仅从构造函数中设置属性。

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.

在 Visual Studio 2015 附带的 C# 6.0 中,有一项更改允许从构造函数中设置仅获取属性。并且仅来自构造函数。

因此,代码可以简化为仅获取一个属性:

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

   public string Value { get; }
}

关于c# - 仅通过构造函数设置类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2357444/

相关文章:

javascript - 如何创建具有不可变属性的 javascript 类

c++ - 类 header.h 不包含在 main 中

php - 从另一个方法获取 php 构造函数参数值和名称

C# Help Basic in 矩阵

c# - 如何重写此 Linq 查询以避免使用 FirstOrDefault?

spring-boot - 是否可以读取@Repository 中的属性文件值?

c# - 在 C# 类中对属性进行排序

c# - 有没有办法在构造函数中强制显式参数类型?

c# - ASP.NET MVC设计问题

c# - 转到定义并查找所有引用在 Visual Studio 中不起作用