【发布时间】:2017-01-27 21:25:23
【问题描述】:
我在 2009 年 5 月 8 日 13:29 看到了 Marc Gravell 的回答 :
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; } }
但是我不明白为什么要创建readonly WriteOnce<T>,如果它的值是private,并且它使用的属性Value只能设置一次。
我也不明白为什么要创建一个属性Name,它只启用get而不启用set:
1.你不能设置名称的值,因为它是只读的并且
2.你不能通过属性设置它的值,因为它只能获取。
【问题讨论】:
标签: c# templates properties get set