有只在C#中设置属性一次的方式只在、属性、方式

2023-09-02 10:30:17 作者:疼痛、在蔓延

我正在寻找一种方式,让在C#对象属性被一次只设置。这很容易写的code要做到这一点,但我宁愿使用一个标准的机制,如果存在的话。

I'm looking for a way to allow a property in a C# object to be set once only. It's easy to write the code to do this, but I would rather use a standard mechanism if one exists.


public OneShot<int> SetOnceProperty { get; set; }

我希望发生的是,该属性可以被设置,如果它尚未设置,但是,如果已被设定之前抛出异常。它应有的功能就像一个空值,我可以检查,看它是否已经被设置与否。

What I want to happen is that the property can be set if it is not already set, but throw an exception if it has been set before. It should function like a Nullable value where I can check to see if it has been set or not.

推荐答案

没有为此在TPL在.NET 4.0中直接支持;在此之前只是做了检查自己......这是不是很多行,从我记得...

There is direct support for this in the TPL in .NET 4.0; until then just do the check yourself... it isn't many lines, from what I recall...

是这样的:

public sealed class WriteOnce<T>
{
    private T value;
    private bool hasValue;
    public override string ToString()
    {
        return hasValue ? Convert.ToString(value) : "";
    }
    public T Value
    {
        get
        {
            if (!hasValue) throw new InvalidOperationException("Value not set");
            return value;
        }
        set
        {
            if (hasValue) throw new InvalidOperationException("Value already set");
            this.value = value;
            this.hasValue = true;
        }
    }
    public T ValueOrDefault { get { return value; } }

    public static implicit operator T(WriteOnce<T> value) { return value.Value; }
}

然后用,例如:

Then use, for example:

readonly WriteOnce<string> name = new WriteOnce<string>();
public WriteOnce<string> Name { get { return name; } }
 
精彩推荐
图片推荐