开发者

How to specify a generic type should be marked with an attribute?

I know I can:

public class SampleClass<TSerializable>
    where TSerializable : ISerializ开发者_开发知识库able

How can I write a SampleClass that accepts only classes marked with the SerializableAttribute instead?


You can't do this at the compiler, short of something like an fxcop add in.

The best you can do is check (once) at runtime, perhaps via a static constructor that verifies the T in question and throws an error for your unit tests to catch:

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
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜