【发布时间】:2019-08-21 19:52:43
【问题描述】:
我有一个静态类,其中包含我的类的一大堆实例。 MyThing 的所有实例都在此处定义。
public static class AllMyThings
{
public static MyThing first { get; } = new MyThing(name = "Foo", otherProperty = "1");
public static MyThing second { get; } = new MyThing(name = "Bar", otherProperty = "50");
...
}
在我的代码的其他地方,我有想要添加属性的方法。我希望这些属性的值来自这些类实例。像这样的
[MyAttribute(AllMyThings.first.name)
public void MyMethod()
这样做会给我错误
属性参数必须是属性参数类型的常量表达式、typeof表达式或数组创建表达式
我不能将first 定义为常量,因为它是MyThing 的一个实例。我能想到的唯一方法就是拥有这样的东西
public static class AllMyThings
{
public const string firstName = "Foo";
public const string secondName = "Bar";
public static MyThing first { get; } = new MyThing(name = firstName, otherProperty = "1");
public static MyThing second { get; } = new MyThing(name = secondName, otherProperty = "50");
}
[MyAttribute(AllMyThings.firstName)
public void MyMethod()
但我想避免代码的其他部分现在必须使用 first 和 firstName 而不仅仅是 first。
还有其他选择吗?
【问题讨论】:
-
您唯一的其他选择是在属性的行为中引用
AllMyThings类型,但您不能将任何值传递给您的属性,超出异常消息中提到的限制 -
看来你做错了什么。您的情况应该有一个有效的解决方案。但案情不明。您能否详细说明您正在尝试解决的实际问题?
-
属性必须在编译时解析,所以你不能使用在运行时可以改变的东西。你到底想用这个属性做什么?
-
实际上没有办法将引用的属性公开为常量。您能否将常量设置为
internal,这样至少曝光仅限于当前程序集?
标签: c#