C#对象的字符串和背部 [英] C# object to string and back

查看:101
本文介绍了C#对象的字符串和背部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题:
我有一个动态的codecompiler。至极可以编译的代码SNIPPIT。的去代码的其余部分。 (进口,命名空间,类,主要功能)已经存在。所述SNIPPIT获得插入到,然后它被编译到装配和执行。这是用户是如何能够执行代码SNIPPIT。主要功能(其中执行SNIPPIT)具有对象的返回类型。这SNIPPIT被一个远程计算机上执行。该代码是由客户端发送到网络服务器。远程计算机从网络服务器中读出的代码,并执行它。在远程计算机上,我可以
轻松查看返回的对象和它的值的类型。 。豪尔我只能字符串发送到Web服务器

My problem: I have a dynamic codecompiler. Wich can Compile a snippit of code. The rest of de code. (imports, namespace, class, main function) is already there. The snippit get inserted into that and then it is compiled to an assembly and executed. This is how user is able execute code snippit. The main function (where the snippit is executed) has a return type of object. This snippit gets executed on a remote computer. The code is send by the client to a webserver. The remote computer reads out the code from the webserver and executes it. On the remote computer i can easily view the type of the returned object and its value. Hower i can only send strings to the webserver.

问:我如何conert一个对象转换成字符串,不管是什么类型的?我如何将其转换回?

Question: how do i conert a object into a string, no matter what the type is and how do i convert it back?

尝试:我试图用的ToString(),使用整型,字符串,双和布尔时工作正常。但是,随着图像或其他类型是不工作ofcourse,因为我还需要能够将其转换回:)

Tried: i tried using ToString(), that works fine when using int, string, double and bool. But with an image or an other type is doesnt work ofcourse because i also need to able to convert it back :)

我会很高兴,如果有人能帮助我:)

I would glad if somebody Could help me :)

问候

推荐答案

序列化使用BinaryFormatter的对象,然后返回字节作为一个字符串(Base64编码)。这样做向后向你的对象了。

Serialize the object using the BinaryFormatter, and then return the bytes as a string (Base64 encoded). Doing it backwards gives you your object back.

public string ObjectToString(object obj)
{
   using (MemoryStream ms = new MemoryStream())
   {
     new BinaryFormatter().Serialize(ms, obj);         
     return Convert.ToBase64String(ms.ToArray());
   }
}

public object StringToObject(string base64String)
{    
   byte[] bytes = Convert.FromBase64String(base64String);
   using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
   {
      ms.Write(bytes, 0, bytes.Length);
      ms.Position = 0;
      return new BinaryFormatter().Deserialize(ms);
   }
}

这篇关于C#对象的字符串和背部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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