开发者

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 ther开发者_如何学JAVAe 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜