环境:c#读取一段javascript代码,并执行。用的是ScriptControl 。想把c#中的Corp对象怎么样变成
javascipt对象obj,传到方法test并执行。代码如下Corp corp=new Corp();
corp.Name="test";
ScriptControl vScriptControl = new ScriptControl();
vScriptControl.Language = "JavaScript";
vScriptControl.ExecuteStatement(@"
function test(obj)
{
  return obj.name
}");//vScriptControl.Eval(test()).ToString()
上面的代码执行一般的运算是没有问题的如:test(){return 1+1}
怎么样c#对象也能在javascript中使用。
各位大虾有什么好的思路。

解决方案 »

  1.   

    把对象的属性ToString()转换成js里的变量试试看,一种不成熟的思路,以前这么做过。
      

  2.   

    答案就是JSON看看这个http://learnitfromvince.blogspot.com/2008/03/using-json-in-cnet.html 
      

  3.   

    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.InteropServices;namespace WindowsFormsApplication1
    {
        [ComVisible(true)]
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        public void Alert(object obj)
            {
                MessageBox.Show(obj.ToString());
            }        private void Form1_Load(object sender, EventArgs e)
            {
                MSScriptControl.IScriptControl sc = new MSScriptControl.ScriptControlClass();
                sc.Language = "JavaScript";
                sc.AddObject("G", this, false);            sc.AddCode(@"
                        function test(abc)
                        {
                            G.Alert(abc.Text);
                        }");                       object[] para = new object[] { this };
                
                sc.Run("test",ref para);
            }
        }
    }
      

  4.   

    使用vScriptControl.ExecuteStatement方法我没有试,其中sc.AddObject("G", this, false); 是指加入一个全局变量,好象IE中使用window对象一样,他是IE带进来的(个人理解)
    我们自己开发的程序中,你的程序即成为了宿主,也要以提供对象。
    当然也可以带进一些临时对象:object[] para = new object[] { this }; sc.Run("test",ref para); 这句中的para就是临时的。
    c#与js中的对象不是完全一致的,我在使用过程中发现有些类型直接在js中做“==”比较时,结果是错误的,这也是正常的,c#是强类型化的
    而js却是弱类型的。[ComVisible(true)]
        public partial class Form1 : Form
    其中的comvisible很重要,否则js中是识别不到这个类的,也就是说你可以把自定义的对象带进js中,但是一定要加上这个属性。