如何指定泛型类型应该用属性标记?

时间:2009-12-01 16:21:08

标签: c# .net generics attributes

我知道我可以:

public class SampleClass<TSerializable>
    where TSerializable : ISerializable

如何编写仅接受使用SerializableAttribute标记的类的SampleClass?

1 个答案:

答案 0 :(得分:3)

你不能在编译器上这样做,缺少类似fxcop的内容。

你可以做的最好的事情是在运行时检查(一次),也许是通过一个静态构造函数来验证有问题的T并为你的单元测试引发错误:

public class SampleClass<TSerializable> {
    static SampleClass() {
        if(!Attribute.IsDefined(typeof(TSerializable),
                typeof(SerializableAttribute))) {
            throw new InvalidOperationException("Not [Serializable]:" +
                typeof(TSerializable).Name);
        }
    }
}

[Serializable] class Foo { }
class Bar { }

static class Program {
    static void Main() {
        new SampleClass<Foo>(); // ok
        new SampleClass<Bar>(); // fail
    }
}