str*_*QNA 8 c# generics reflection compile-time-constant compile-time
我正在尝试实现泛型类.它应该有一个属性,该属性需要一个编译时常量,我想将其设置为参数类型的名称.像这样的东西:
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
}
}
Run Code Online (Sandbox Code Playgroud)
但是因为typeof(T).Name在运行时进行评估,所以它不起作用.可能吗?
我认为这不是使用属性的正确方法。属性用于向类添加特定特征。它们是您在编译时添加到类中以便在运行时查询和使用的标签。您正在尝试在运行时添加属性并如何使用它?为什么要使用属性来保存运行时可用的信息?
可以在运行时轻松查询类型的名称。我认为您应该提供更多关于您想要实现的目标的信息,否则我认为使用TypeName属性可能就足够了。