【发布时间】:2008-10-21 12:45:09
【问题描述】:
我想做一个只接受可序列化类的泛型类,可以用 where 约束来完成吗?
我正在寻找的概念是这样的:
public class MyClass<T> where T : //[is serializable/has the serializable attribute]
【问题讨论】:
标签: c# generics attributes constraints where
我想做一个只接受可序列化类的泛型类,可以用 where 约束来完成吗?
我正在寻找的概念是这样的:
public class MyClass<T> where T : //[is serializable/has the serializable attribute]
【问题讨论】:
标签: c# generics attributes constraints where
不,恐怕不会。您可以对约束做的唯一事情是:
where T : class - T 必须是引用类型where T : struct - T 必须是不可为空的值类型where T : SomeClass - T 必须是 SomeClass 或派生自它where T : ISomeInterface - T 必须是 ISomeInterface 或实现它where T : new() - T 必须有一个公共的无参数构造函数各种组合都是可行的,但不是全部。与属性无关。
【讨论】:
where T : ISerializable 不会这样做吗?
我所知道的;你不可以做这个。 您是否考虑过添加“初始化”方法或类似方法?
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");
}
我没有测试过这段代码,但我希望你明白我的意思。
【讨论】:
不怕。你能做的最好的就是对Type.IsSerializable进行运行时检查。
【讨论】:
如果您正在寻找任何可序列化的类,我认为您不走运。如果您正在寻找您创建的对象,您可以创建一个可序列化的基类,并让您想要支持的每个类都派生自它。
【讨论】:
我知道这是旧的,但我正在使用静态构造函数进行检查。它是稍后的,但允许您在运行时抛出错误。
【讨论】: