c# - 如何使属性设置一次且不能更改?

标签 c# properties constructor

我有一个 Message 类,它具有三个属性 Content、Type 和 UniqueId。创建 Message 对象时,Content 和 Type 是已知的,因此我可以将它们传递给类的构造函数,并将 Content 和 Type 属性设为只读,这样它们的值就不能再更改了。但是,对于 UniqueId,我需要在创建对象后在我的代码中计算它,并将值赋给 UniqueId 属性。由于我无法将 UniqueId 传递给构造函数并将此属性设置为只读,我想知道是否有一种方法可以在设置属性 UniqueId 后,不再更改其值?

public class Message
{
    private readonly string content;
    private readonly AuditMessageType type;
    private Guid messageUId;

    public Message(string syslogMessage, AuditMessageType messageType, Guid messageUniqueId = new Guid())
    {
        content = syslogMessage;
        type = messageType;
        messageUId = messageUniqueId;
    }

    public string Message
    {
        get { return message; }
    }

    public AuditMessageType Type
    {
        get { return type; }
    }

    public Guid MesageUniqueId
    {
        get { return messageUId; }
        set { messageUId = value; } // How to make UniqueId property set once here? It cannot be pass in the constructor, as it needs to computed in the code after the object has been created. 
    }
}

最佳答案

你不能简单地创建一个保护标志吗?

bool wasSetMessageId = false;
public Guid MesageUniqueId
{
    get { return messageUId; }
    set 
    {
       if (!wasSetMessageId) 
       {
          messageUId = value;
          wasSetMessageId = true;
       } 
       else
       {
          throw new InvalidOperationException("Message id can be assigned only once");
       }
    } 
}

关于c# - 如何使属性设置一次且不能更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24798711/

相关文章:

c# - 如何在智能手机上显示 "busy"对话框(纺车)

c# - System.Data.DataRowCollection' 不包含 'ToList' 的定义并且没有扩展方法 'ToList' 接受第一个参数

c# - 覆盖插件 NopCommerce 4.3 的 View

java - 构造函数不创建对象——Java

未调用 C++ 默认构造函数

java - 从类扩展构造函数

c# - 在 [Authorize(Roles)] 上使用枚举 [Flags] 和按位运算符

c# - 按属性名从列表中选择常量

java - Spring+Maven 属性文件未加载

jdbc - Camel : Aggregator doesn't persist Exchange properties