jua*_*uan 32 c# generics attributes constraints where
我想创建一个只接受可序列化类的泛型类,可以用where约束来完成吗?
我正在寻找的概念是这样的:
public class MyClass<T> where T : //[is serializable/has the serializable attribute]
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 38
不,我不敢.你可以用限制做的唯一事情是:
where T : class
- T必须是参考类型where T : struct
- T必须是不可为空的值类型where T : SomeClass
- T必须是SomeClass或派生自它where T : ISomeInterface
- T必须是ISomeInterface或实现它where T : new()
- T必须有一个公共无参数构造函数各种组合是可行的,但不是全部.关于属性没什么.
我知道的; 你不能做这个.你有没有添加'Initialize'方法或类似的东西?
public void Initialize<T>(T obj)
{
object[] attributes = obj.GetType().GetCustomAttributes(typeof(SerializableAttribute));
if(attributes == null || attributes.Length == 0)
throw new InvalidOperationException("The provided object is not serializable");
}
Run Code Online (Sandbox Code Playgroud)
我没有测试过这段代码,但我希望你明白我的观点.