【发布时间】:2011-11-28 01:56:50
【问题描述】:
考虑以下属性。
internal class NiceAttribute : Attribute
{
private string _stuff;
public string Stuff
{
set { _stuff = value; }
}
}
当我尝试使用属性[Nice(Stuff = "test")] 时,编译器会给出以下错误。
'Stuff' 不是有效的命名属性参数。命名属性 arguments 必须是非 readonly、static 或 const 的字段,或 read-write 属性是公共的,不是静态的。
要求属性可读的原因是什么?
更新
我将尝试概述我的用例,以在属性上具有只写属性。
interface ISettingsBuilder
{
Settings GetSettings();
}
class SettingsAttribute : Attribute, ISettingsBuilder
{
private readonly IDictionary<string, object> _settings =
new Dictionary<string, object>();
public Settings GetSettings()
{
// Use _settings to create an immutable instance of Settings
}
public string Stuff
{
set { _settings["Stuff"] = value; }
}
// More properties ...
}
ISettingsBuilder 可能还有其他实现。例如,它提供了一个很好的 API 来通过代码构建设置。
我最终通过抛出 NotImplementedException 来实现我的 getter。
public string Stuff
{
get { throw new NotImplementedException(); }
set { _settings["Stuff"] = value; }
}
你能想出更好的方法来做这样的事情吗?
【问题讨论】:
-
现在正是 John Skeet 或 Eric Lippert 出现的好时机。我碰巧看到 Jon Skeet 正在编辑标签 :)
-
我没有一个好的答案,但您为什么希望它不可读?
-
@µBio:因为不需要?该属性可以读取后备存储。如果你愿意的话,它被称为封装。
-
@sehe:我查看了,我检查了规范,我投了赞成票……规范声明它必须是,但没有给出任何理由。
-
这可能与“命名参数”的工作方式有关吗?它是我们在 C# 4.0 之前拥有的唯一命名参数,并且它的实现可能会强制这种行为,因为它们可能会创建实例然后设置属性/字段。因此它们不能是只读的、静态的或 const 的。如果它是一个属性,它必须有一个 setter。什么的。
标签: c# attributes properties compiler-errors