序列化匿名类型 [英] Serializing anonymous types

查看:65
本文介绍了序列化匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将匿名类型变量转换为 byte[],我该怎么做?

I'd like to convert anonymous type variable to byte[], how can I do that?

我尝试了什么:

byte[] result;

var my = new
{
    Test = "a1",
    Value = 0
};

BinaryFormatter bf = new BinaryFormatter();

using (MemoryStream ms = new MemoryStream())
{
    bf.Serialize(ms, my); //-- ERROR

    result = ms.ToArray();
}

我有错误:

类型异常'System.Runtime.Serialization.SerializationException' 发生在mscorlib.dll 但未在用户代码中处理

An exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll but was not handled in user code

版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib,版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089]]'在程序集'MyProject,版本= 1.0.0.0,文化=中性,PublicKeyToken=null' 未标记为可序列化.附加信息:类型 '<>f__AnonymousType10`2[[System.String, mscorlib,

Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' in Assembly 'MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.Additional information: Type '<>f__AnonymousType10`2[[System.String, mscorlib,

有人可以帮我吗?我做错了什么?或者这是不可能的?

Can somebody help me? What I'm doing wrong? Or this is not possible to do?

推荐答案

只需创建一个可序列化的类

Just create a serializable class

[Serializable]
class myClass
{
    public string Test { get; set; }
    public int Value { get; set; }
}

您可以通过以下方式序列化您的对象:

And you can serialize your object the following way:

byte[] result;
myClass my = new myClass()
{
    Test = "a1",
    Value = 0
};
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
    bf.Serialize(ms, my); //NO MORE ERROR
    result = ms.ToArray();
}

但是我不可能序列化匿名类型

But i'ts not possible to serialize a anonymous type

这篇关于序列化匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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