+ -
当前位置:首页 → 问答吧 → 如何序列化带参数的方法?

如何序列化带参数的方法?

时间:2011-12-18

来源:互联网

我需要在服务端传输一段方法给客户端调用,但参数是客户端的,我做了个实验,没有成功,望告人指教!
C# code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                BinaryFormatter a = new BinaryFormatter();
                System.IO.MemoryStream b = new System.IO.MemoryStream();
                a.Serialize(b, new Action<string>(delegate { method(null); }));
                b.Position = 0;
                dynamic c = a.Deserialize(b);
                c.DynamicInvoke(new object[] { "ds" }); //我想传参数进去,但没用
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public static void method(string t)
        {
            MessageBox.Show(t);
        }
    }
}


作者: aa6103848252   发布时间: 2011-12-18

a.Serialize(b, new Action<string>(delegate { method(null); }));
=>
a.Serialize(b, new Action<string>(_ => method(_)));

作者: Sandy945   发布时间: 2011-12-19

a.Serialize(b, new Action<string>(t => method(t)));

更容易理解些

作者: Sandy945   发布时间: 2011-12-19

引用 2 楼 sandy945 的回复:
a.Serialize(b, new Action<string>(t => method(t)));

更容易理解些


t => method(t)

敢问这属于哪块知识了

作者: xl_0715   发布时间: 2011-12-19

其实这样写更容易理解:
a.Serialize(b, new Action<string>(method));

作者: qldsrx   发布时间: 2011-12-19

或者

a.Serialize(b, new Action<string>(delegate(string s) { method(s); }));


BTW: t => method(t) 是 lambada 表达式, 有些语言里叫Closure
t => method(t) 意思差不多等于 var f(var t) { return method(t); } 其中的 var 由编译器根据语境来推理出适当的类型。如果第一个var推导结果为 void, 则后边 的return 去掉

作者: todd_wang   发布时间: 2011-12-19