我希望创建一个通用类,只接受可序列化的类,这可以通过where约束实现吗?
我要实现的概念是这样的:
public class MyClass<T> where T : //[is serializable/has the serializable attribute]
我希望创建一个通用类,只接受可序列化的类,这可以通过where约束实现吗?
我要实现的概念是这样的:
public class MyClass<T> where T : //[is serializable/has the serializable attribute]
where T : class
- T 必须是引用类型where T : struct
- T 必须是非可空值类型where T : SomeClass
- T 必须是 SomeClass 或从其派生的类where T : ISomeInterface
- T 必须是 ISomeInterface 或实现它的类where T : new()
- T 必须有一个公共的无参数构造函数据我所知,你不能这样做。你考虑过添加“初始化”方法或类似的东西吗?
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");
}
如果你正在寻找任何可序列化的类,我想你会很失望。如果你正在寻找你自己创建的对象,你可以创建一个可序列化的基类,并让你想要支持的每个类都从它派生。