How can I make a property "Write Once Read Many" in VB.NET?

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?


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.


我知道已经差不多3年了,但这是我认为更好的解决方案:

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; }
}

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.

链接地址: http://www.djcxy.com/p/43946.html

上一篇: MacPorts Apache2在启动时停止启动

下一篇: 如何在VB.NET中创建一个属性“Write Once Read Many”?