【问题标题】:Use Microsoft Scripting Control to evaluate 'If' expressions (via c#)使用 Microsoft Scripting Control 评估“If”表达式(通过 c#)
【发布时间】:2009-04-05 12:53:52
【问题描述】:

我有一些使用 Microsoft Scripting Control 来评估某些表达式的 c# 代码:

using MSScriptControl; // references msscript.ocx

ScriptControlClass sc = new ScriptControlClass();
sc.Language = "VBScript";
sc.AllowUI = true;

try
{
    Console.WriteLine(sc.Eval(txtEx.Text).ToString());
}
    catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

(txtEx 是一个简单的文本字段)

数值表达式:“6+4”、“cos(34)”、“abs(-99)”、“round(1.234, 2)”等都可以

布尔表达式:“true or false”、“1=2”都可以

但是我如何评估一个简单的“如果”呢?我试过“if(true, 2, 3)”、“iif(true, 2, 3)”、“if (true) then 2 else 3”和“if (true) then 2 else 3 endif”

谁能帮我评估简单的条件表达式?非常感谢任何帮助!

相对湿度

【问题讨论】:

  • 这个问题很老了。如果有帮助,您应该接受一个!

标签: c# .net vbscript expression


【解决方案1】:

尝试将您的 IF 表达式包装在一个函数中

Function test
   if (true) then
      return true
   else
      return false
   end if
End function

将函数添加到控件中,然后使用Run

Result = ScriptControl.Run("Test")

(上面的代码没有经过测试,但应该可以正常工作)

查看此链接了解更多信息

http://support.microsoft.com/kb/184740

【讨论】:

    【解决方案2】:
    using MSScriptControl; // references msscript.ocx
    
    ScriptControlClass sc = new ScriptControlClass();
    sc.Language = "VBScript";
    sc.AllowUI = true;
    
    // VBScript engine doesn’t have IIf function
    // Adding wraper IIF function to script control.
    // This IIF function will work just as VB6 IIf function.
    sc.AddCode(@"Function IIF(Expression,TruePart,FalsePart)
                    If Expression Then
                        IIF=TruePart
                    Else
                        IIF=FalsePart
                    End IF
                End Function");
    try
    {
        //define x,y variable with value
        sc.AddCode(@"x=5
                    y=6");
        //test our IIF 
        Console.WriteLine(sc.Eval("IIF(x>y,x,y)").ToString());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    

    【讨论】:

      【解决方案3】:

      您应该考虑使用作为 Windows Workflow Foundation 一部分的表达式评估引擎。评估者和设计者都可以与WF分开使用。

      【讨论】:

        【解决方案4】:
        if (true) then return 2 else return 3
        

        【讨论】:

          【解决方案5】:

          感谢您的提示!在 Brummo 的帮助下,经过更多的试验,这似乎可行:

          txtEx 包含以下文本:

          function test
            if (1=1) then 
              test = true
            else 
              test = false
            end if
          end function
          

          然后

          sc.AddCode(txtEx.Text);

          object[] myParams = { };
          Console.WriteLine(sc.Run("Test", ref myParams).ToString());
          

          这并不理想,因为我真的想评估一个表达式,而不是构建、加载和评估函数。 (如果评估,我很惊讶 IIF 不适用于简单的一行)。

          【讨论】:

            猜你喜欢
            • 2012-04-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-11-11
            • 1970-01-01
            • 2018-05-19
            • 1970-01-01
            相关资源
            最近更新 更多