9

我正在尝试实现一个泛型类。它应该有一个属性,该属性带有一个编译时常量,我想将其设置为参数类型的名称。像这样的东西:

namespace Example
{
    public class MyGeneric<T>
    {
        [SomeAttribute(CompileTimeConstant)]
        public int MyProperty { get; set; }

        private const string CompileTimeConstant = typeof(T).Name; // error CS0133:
        // The expression being assigned to `Example.MyGeneric<T>.CompileTimeConstant' must be constant
    }
}

但是因为typeof(T).Name是在运行时评估的,所以它不起作用。可能吗?

4

1 回答 1

1

我认为这不是使用属性的正确方法。属性用于向类添加特定特征。它们是您在编译时添加到类中以便在运行时查询和使用的标记。您正在尝试在运行时添加属性并如何使用它?为什么要使用属性来保存运行时可用的信息?

可以在运行时轻松查询类型的名称。我认为您应该提供更多有关您想要实现的目标的信息,否则我认为使用TypeName属性可能就足够了。

于 2014-06-04T17:48:17.220 回答