【问题标题】:How can I get a generic parameter type name at compile time?如何在编译时获取泛型参数类型名称?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我想使用ConfigurationCollectionAttribute 创建class ConfigurationSectionOfCollection&lt;TConfigurationElement&gt; where TConfigurationElement : ConfigurationElement,它将使用名称为TConfigurationElement 的配置集合作为集合的XML 标记名称。这样我就不必为我使用它们的 5 次中的每一次复制配置集合和部分的代码。如果我想更改其中一个部分,它的类可能会停止从 ConfigurationSectionOfCollection&lt;T&gt; 继承。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多