【发布时间】:2014-07-23 02:03:18
【问题描述】:
我正在尝试实现一个泛型类。它应该有一个属性,该属性带有一个编译时常量,我想将其设置为参数类型的名称。像这样的:
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 是在运行时评估的,所以它不起作用。有可能吗?
【问题讨论】:
-
typeof在编译时进行评估。 -
@DanielA.White 将其更改为
typeof(T).Name。
标签: c# generics reflection compile-time compile-time-constant