我有以下方法声明:
public static bool SerializeObject<T>(string filename, T objectToSerialize){
我想将 T
限制为使用 [Serializable]
属性修饰的类型。
以下内容不起作用,因为“属性‘System.SerializableAttribute’在此声明类型上无效。它仅在‘Class、Enum、Struct、Delegate’声明上有效。”:
public static bool SerializeObject<T>(string filename, [Serializable] T objectToSerialize)
我了解必须为属性设置 AttributeUsageAttribute(AttributeTargets.Parameter)
才能使用上述内容,并且 [Serializable]
属性没有此设置.
有没有办法将 T
限制为用 [Serializable]
属性标记的类型?
最佳答案
Is there a way to restrict
T
to types marked with the[Serializable]
attribute?
不,没有办法使用通用约束来做到这一点。这些限制在规范中有明确说明,这不是其中之一。
但是,你可以写一个扩展方法
public static bool IsTypeSerializable(this Type type) {
Contract.Requires(type != null);
return type.GetCustomAttributes(typeof(SerializableAttribute), true)
.Any();
}
然后说
Contract.Requires(typeof(T).IsTypeSerializable());
不,这不是一回事,但这是您能做的最好的。对泛型的限制相当有限。
最后,你可以考虑说
where T : ISerializable
同样,这不是一回事,但这是需要考虑的事情。
关于c# - C#泛型的属性限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9910949/