c# - 如何使用通用的 getter 和 setter 设置只读属性的值?

标签 c# properties

不确定我的措辞是否正确......但我有以下代码:

    public Guid ItemId
    {
        get;
    }

    public TransactionItem()
    {
        this.ItemId = Guid.Empty;
    }

当然,我遇到的是只读问题……我确实理解。无论如何设置此属性值而不必执行以下操作:

    Guid _itemId = Guid.Empty;
    public Guid ItemId
    {
        get
        {
            return _itemId;
        }
        set
        {
            _itemId = value;
        }
    }

    public Guid ItemId
    {
        get;
        internal set;
    }

提前致谢!

最佳答案

我会这样做:

public Guid ItemId
{
    get;
    private set; // can omit as of C# 6 
}

public TransactionItem()
{
    this.ItemId = Guid.Empty;
}

当然,它可以在这个类中设置,但是既然你正在写它,我希望你有意识,不要违背自己的意图......

在我看来,从外部来看,诸如只读属性之类的东西最为重要。从内心看,它是什么并不重要,因为在那里,你就是国王 =)

关于c# - 如何使用通用的 getter 和 setter 设置只读属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/565075/

相关文章:

c# - 无法在 ASP.NET MVC 中初始化 SelectList

c# - 使用 System.Transactions 时保存点的替代方法

c# - 如何覆盖 WinForms RichTextBox 的 Ctrl+Shift+0(零)?

SVN忽略问题

jquery - 使用 jQuery 更改 html 背景图像

.net - 组装问题/难题中的只读与属性

properties - 如何指定c :\users\public (%PUBLIC%) in WiX?

c# - 如何阻止按钮事件在 ASP.NET MVC 中发布?

c# - 将数据发送到特定的 IP 和端口

java - 如何 "hide"敏感的系统属性,例如Java应用程序设置的密码?