如何使属性“一次写入多次读取”在 VB.NET 中?

发布于 2024-08-17 23:20:59 字数 210 浏览 8 评论 0原文

使类属性“写入一次,读取多次”以便只能设置该属性一次的最佳方法是什么?

我知道我可以传递构造函数中的所有属性并使它们只读,但在有很多属性的情况下,我不想要一个具有 20 多个参数的构造函数。

另外,我意识到我可以“推出自己的”设置器,但必须为每个属性执行此操作似乎是一堆冗余编码。

在 VB 2008 .NET 3.5 中是否有一种干净的方法可以做到这一点?

What is the best way to make a class property "Write Once, Read Many" such that you can only set the property once?

I know that I could pass all the properties in the constructor and make them ReadOnly, but in cases with a lot of properties I don't want a constructor that has 20+ arguments.

Also, I realize I can "roll my own" setters, but having to do that for every property seems like a bunch of redundant coding.

Is there a clean way to do this in VB 2008 .NET 3.5?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红焚 2024-08-24 23:20:59

一次写入属性永远不会“干净”。

我建议创建一个构建器/工厂类以避免 20 参数 CTor。
(是的,我知道这是相当多的打字)

这里类似的讨论:
我应该使用一次设置变量吗?

[编辑]此外,即使您坚持认为,除了滚动您自己的设置器之外,我也看不到其他选择,这也需要大量输入。

A Write Once Property is never "clean".

I'd recommend to create a builder/factory class to avoid the 20 param CTor.
(Yes, I know it is quite some typing)

Similar discussion here:
Should I use set once variables?

[edit] Furthermore, even if you insist I don't see another option than rolling your own setters, which is a lot of typing, too.

别闹i 2024-08-24 23:20:59

我知道已经快三年了,但这是我认为更好的解决方案:

public class Site
{
    private int miID;

    public Site(int iNewID, string sName)
    {
        miID = iNewID;
        Name = sName;
    }
    // The ID property can only be set once in the constructor
    public int ID
    {
        get { return miID; }
    }
    public string Name { get; set; }
}

I know it's been almost 3 years, but here's my solution which I think is better:

public class Site
{
    private int miID;

    public Site(int iNewID, string sName)
    {
        miID = iNewID;
        Name = sName;
    }
    // The ID property can only be set once in the constructor
    public int ID
    {
        get { return miID; }
    }
    public string Name { get; set; }
}
心碎无痕… 2024-08-24 23:20:59

“最干净”的方法是根本不这样做并使用自动属性。我也看不出有必要。它们只能被写入一次真的那么重要吗?如果是这样,我肯定会选择一个将所有属性的值作为参数的构造函数。

The "cleanest" way would be not to do it at all and use auto properties. I fail to see the need for it too. Is it really that important that they can only be written once? If so I would definitely go with a constructor that takes values for all the properties as parameters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文