[英]How can I get the generic type parameter of the 'this' parameter in an extension method?
[英]How can I get a generic parameter type name at 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
}
}
但是因为typeof(T).Name
是在运行时求值的,所以它不起作用。 可能吗?
我认为这不是使用属性的正确方法。 可以使用属性为类添加特定的特征。 它们是您在编译时添加到类中以在运行时查询和使用的标记。 您试图在运行时添加属性,并如何使用它? 为什么要使用属性来保存运行时可用的信息?
类型的名称可以在运行时轻松查询。 我认为您应该提供有关确切要实现的目标的更多信息,否则我认为使用TypeName
属性可能就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.