如何设置一次属性并且不能更改?

use*_*189 1 c# constructor properties

我有一个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. 
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您不能简单地创建一个防护标志吗?

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");
       }
    } 
}
Run Code Online (Sandbox Code Playgroud)