有只在C#中设置属性一次的方式 [英] Is there a way of setting a property once only in C#

查看:178
本文介绍了有只在C#中设置属性一次的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式,让在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; } }

这篇关于有只在C#中设置属性一次的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆