【发布时间】:2014-07-17 08:39:36
【问题描述】:
我有一个 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.
}
}
【问题讨论】:
-
这是我在c#中真正怀念的东西
标签: c# properties constructor