仅通过构造函数设置类的属性 [英] Set properties of a class only through constructor

查看:71
本文介绍了仅通过构造函数设置类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make the properties of class which can only be set through the constructor of the same class.

推荐答案

使属性具有只读的支持字段:

Make the properties have readonly backing fields:

public class Thing
{
   private readonly string _value;

   public Thing(string value)
   {
      _value = value;
   }

   public string Value { get { return _value; } }
}

这篇关于仅通过构造函数设置类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆