【问题标题】:Only allow generic types that implement attribute [duplicate]只允许实现属性的泛型类型[重复]
【发布时间】:2014-08-20 11:04:14
【问题描述】:

是否可以将泛型类型限制为实现特定属性的类?

如果我有一个名为 MyCustomAttribute 的属性...我想写这样的东西:

public class SomeRandomClass<T>
    where T : MyCustomAttribute
{
}

但不是其中 T 是 MyCustomAttribute 的派生类,而是实现该属性的类。

谢谢

编辑:

我的意思是这样实现的:

[MyCustomAttribute]
public class SomeOtherClass
{
}

【问题讨论】:

  • 从类派生和实现有什么区别?

标签: c# generics custom-attributes


【解决方案1】:

如果您正在寻找需要使用某些属性标记类型参数的泛型参数约束,那么这是不可能的。

以下是可能的限制列表:Constraints on Type Parameters (C# Programming Guide)。您可以为类型参数添加以下六个约束

  1. 成为值类型
  2. 作为引用类型
  3. 拥有一个公共的无参数构造函数
  4. 是或从指定的基类派生
  5. 实现指定接口
  6. 是或源自其他论点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多