2010-06-22 41 views
3

在.net中,如果我有一个通用类SomeClass<T>,是否可以使用where关键字来要求T是具有某个属性的类?例如:.net中泛型类型的属性约束?

[SomeAttribute] 
class MyClass 
{ 
    ... 
} 

class AnotherClass<T> where T : Attribute(SomeAttribute) 
{ 
    ... 
} 

回答

3

不,这是不可能的。

最接近你可以做的是要求类实现一个特定的接口。

2

,你不行,但你可以通过检查静态构造函数的属性避开这个问题:

public class MyType<T> { 
    static MyType() { 
     // not compile checked, something like: 
     if (!Attribute.IsDefined(typeof(T), typeof(MyAttribute)) 
      throw new ArgumentException(); // or a more sensible exception 
    } 
}