我如何添加一个类型约束,包括在一个通用的方法序列化的东西? [英] How can I add a type constraint to include anything serializable in a generic method?

查看:168
本文介绍了我如何添加一个类型约束,包括在一个通用的方法序列化的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的泛型方法需要序列传递给它的对象,但只是坚持认为它实现了ISerializable似乎并没有工作。例如,我有一个结构的序列化为xml就好了一个Web服务(标有Seri​​alizableAttribute)返回,但是,正如预期的那样,C#编译器抱怨。

My generic method needs to serialize the object passed to it, however just insisting that it implements ISerializable doesn't seem to work. For example, I have a struct returned from a web service (marked with SerializableAttribute) that serializes to xml just fine, but, as expected, the C# compiler complains.

有没有一种方法,我可以检查对象序列化之前试图序列,或者更好的是,使用其中,关键字来检查对象的一种方式适合呢?

Is there a way I can check the object is serializable before attempting to serialize it, or, better still, a way of using the where keyword to check the object is suitable?

下面是我完整的方法:

public static void Push<T>(string url, T message)
        where T : ISerializable
{
    string xml = SerializeMessage(message);

    // Send the message to Amazon SQS
    SendMessageRequest sendReq = new SendMessageRequest { QueueUrl = url, MessageBody = xml };
    AmazonSQSClient client = new AmazonSQSClient(S3User, S3Pass);
    client.SendMessage(sendReq);
}

和SerializeMessage:

And SerializeMessage:

private static string SerializeMessage<T>(T message)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (StringWriter stringWriter = new StringWriter())
    {
        xmlSerializer.Serialize(stringWriter, message);
        return stringWriter.ToString();
    }
}

如果这是不可能的,什么是执行检查的最佳方法,一个对象在运行时是可序列化

If this isn't possible, what's the best way to perform a check that an object is serializable at runtime?

推荐答案

您不能这样做完全通过通用的限制,但你可以做几件事情,以帮助:

You can't do this totally via generic constraints, but you can do a couple things to help:

1)把对泛型类型在新()约束(以使反序列化的能力,并确保XmlSerializer的不抱怨缺少默认构造函数中):

1) Put the new() constraint on the generic type (to enable the ability to deserialize and to ensure the XmlSerializer doesn't complain about a lack of default ctor):

where T : new()

2)你的方法处理序列化(或构造函数或其他任何地方,你不必一遍遍重复)的第一行,然后才能执行此检查:

2) On the first line of your method handling the serialization (or constructor or anywhere else you don't have to repeat it over and over), you can perform this check:

if( !typeof(T).IsSerializable && !(typeof(ISerializable).IsAssignableFrom(typeof(T)) ) )
    throw new InvalidOperationException("A serializable Type is required");

当然,还是有试图序列化类型时,运行时异常的可能性,但是这将覆盖最明显的问题。

Of course, there's still the possibility of runtime exceptions when trying to serialize a type, but this will cover the most obvious issues.

这篇关于我如何添加一个类型约束,包括在一个通用的方法序列化的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆