Chr*_*les 5 c# generics attributes
我有以下方法声明:
public static bool SerializeObject<T>(string filename, T objectToSerialize){
Run Code Online (Sandbox Code Playgroud)
我想限制T使用该[Serializable]属性修饰的类型.
以下方法不起作用,因为"Attribute'System.SerializableAttribute'在此声明类型上无效.它仅对'Class,Enum,Struct,Delegate'声明有效.":
public static bool SerializeObject<T>(string filename, [Serializable] T objectToSerialize)
Run Code Online (Sandbox Code Playgroud)
我知道AttributeUsageAttribute(AttributeTargets.Parameter)必须为属性设置才能使用上面的[Serializable]属性并且该属性没有这个集合.
有没有办法限制T标有[Serializable]属性的类型?
有没有办法限制
T标有[Serializable]属性的类型?
不,没有办法使用通用约束来做到这一点.这些限制在规范中明确规定,这不是其中之一.
但是,您可以编写扩展方法
public static bool IsTypeSerializable(this Type type) {
Contract.Requires(type != null);
return type.GetCustomAttributes(typeof(SerializableAttribute), true)
.Any();
}
Run Code Online (Sandbox Code Playgroud)
并说
Contract.Requires(typeof(T).IsTypeSerializable());
Run Code Online (Sandbox Code Playgroud)
不,这不是一回事,但它是你能做的最好的事情.对泛型的限制相当有限.
最后,你可以考虑说
where T : ISerializable
Run Code Online (Sandbox Code Playgroud)
同样,不一样,但需要考虑的事情.