本文介绍了C#泛型的属性限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法声明:

pre code public static bool SerializeObject< T>(string filename,T objectToSerialize){

我想限制 T [Serializable] 属性。



以下操作不起作用,因为Attribute'System.SerializableAttribute'无效在这个声明类型上,它只对'Class,Enum,Struct,Delegate'声明有效。:

  public static bool SerializeObject< T>(string filename,[Serializable] T objectToSerialize)

据我所知,<$ c $必须为属性设置c> AttributeUsageAttribute(AttributeTargets.Parameter)才能使用上述属性,并且 [Serializable] 属性没有这个集合。



有没有办法将 T 限制为标有的类型[可序列化] 属性?

解决方案

不,没有使用通用约束来做到这一点。这些限制在规范中明确说明,这不是其中之一。

然而,你可以写一个扩展方法

  public static bool IsTypeSerializable(this Type type){
Contract.Requires(type!= null);
return type.GetCustomAttributes(typeof(SerializableAttribute),true)
.Any();
}

并说

  Contract.Requires(typeof运算(T).IsTypeSerializable()); 

不,这不是一回事,但它是最好的。对泛型的限制是相当有限的。

最后,你可以考虑说:

pre $ where T:ISerializable

同样的事情,不过是需要考虑的事情。 / p>

I have the following method declaration:

public static bool SerializeObject<T>(string filename, T objectToSerialize){

I want to restrict T to types decorated with the [Serializable] attribute.

The following does not work because "Attribute 'System.SerializableAttribute' is not valid on this declaration type. It is valid on 'Class, Enum, Struct, Delegate' declarations only.":

public static bool SerializeObject<T>(string filename, [Serializable] T objectToSerialize)

I understand that AttributeUsageAttribute(AttributeTargets.Parameter) must be set for the Attribute in order to use the above and that the [Serializable] attribute does not have this set.

Is there a way to restrict T to types marked with the [Serializable] attribute?

解决方案

No, there is not a way to do this using generic constraints. These contraints are clearly spelled out in the specification and this is not one of them.

However, you could write an extension method

public static bool IsTypeSerializable(this Type type) {
    Contract.Requires(type != null);
    return type.GetCustomAttributes(typeof(SerializableAttribute), true)
               .Any();
}

and say

Contract.Requires(typeof(T).IsTypeSerializable());

No, it's not the same thing, but it's the best that you can do. The constraints on generics are fairly limited.

Lastly, you could consider saying

where T : ISerializable

Again, not the same thing, but it's something to consider.

这篇关于C#泛型的属性限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 03:49