【问题标题】:Possible for a class instance property as a value in an attribute可以将类实例属性作为属性中的值
【发布时间】: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()

但我想避免代码的其他部分现在必须使用 firstfirstName 而不仅仅是 first

还有其他选择吗?

【问题讨论】:

  • 您唯一的其他选择是在属性的行为中引用 AllMyThings 类型,但您不能将任何值传递给您的属性,超出异常消息中提到的限制
  • 看来你做错了什么。您的情况应该有一个有效的解决方案。但案情不明。您能否详细说明您正在尝试解决的实际问题?
  • 属性必须在编译时解析,所以你不能使用在运行时可以改变的东西。你到底想用这个属性做什么?
  • 实际上没有办法将引用的属性公开为常量。您能否将常量设置为internal,这样至少曝光仅限于当前程序集?

标签: c#


【解决方案1】:

有一种方法,但您必须为此使用反射。这是属性:

[MyAttribute(typeof(AllMyThings), nameof(AllMyThings.first))
public void MyMethod()

现在您的属性可以正常编译,但为了获取 AllMyThings.first.name 的值,您必须获取 AllMyThings 的类型,通过名称找到静态公共属性,然后检索属性值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 2021-10-07
    • 2011-11-24
    相关资源
    最近更新 更多