c# - C#泛型的属性限制

标签 c# generics attributes

我有以下方法声明:

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/

相关文章:

c# - 什么是折叠一组潜在重叠范围的通用算法?

java - 泛型类型存储在 java 类文件中的什么位置?

html - 使用@helper.inputText ("property"时不在输入框前显示文本)

c# - 在 C# 中使用属性/接口(interface)的区别

c# - 在操作之间传递列表

c# - Zebra EPL/ZPL 上的 .NET 网络套接字打印

c# - 为什么 AuthenticationResult B2C 认证中 accessToken 为空?

Java 泛型查询(上限通配符)

python - 为什么 python 类属性的语义在分配给实例后会发生变化?

c# - 启动 Contract First WCF 或 Web 服务的最佳方式?