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
}
}
精彩评论