C# と VB.NET の質問掲示板

わんくま同盟

ASP.NET、C++/CLI、Java 何でもどうぞ

C# と VB.NET の入門サイト


■103442 / )  Re[3]: C#で関数を含む計算式文字列を処理して計算する
□投稿者/ くま (32回)-(2024/11/20(Wed) 15:40:27)
2024/11/20(Wed) 16:03:36 編集(投稿者)
JScriptバージョン

//----- EasyCalcクラス(開始)
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public class EasyCalc
{
    private System.Type comType = null;
    private dynamic comInstance = null;
    /// <summary>
    /// コンストラクタ
    /// </summary>
    public EasyCalc()
    {
        this.comType = System.Type.GetTypeFromProgID("MSScriptControl.ScriptControl");
        this.comInstance = System.Activator.CreateInstance(this.comType);
        this.comInstance.Language = "JScript";
    }
    /// <summary>
    /// デストラクタ
    /// </summary>
    ~EasyCalc()
    {
        Marshal.ReleaseComObject(this.comInstance);
        this.comInstance = null;
        this.comType = null;
    }

    /// <summary>
    /// 計算式用プロパティ
    /// </summary>
    public string Expression { get; set; } = string.Empty;

    /// <summary>
    /// 計算を実行する。
    /// </summary>
    /// <param name="values">値一覧</param>
    /// <param name="err">エラーの場合、エラー内容。それ以外の場合は、string.Empty。</param>
    /// <returns>計算結果</returns>
    public double GetValue(string values, ref string err)
    {
        err = string.Empty;
        try
        {
            List<string> lstFormula = new List<string>();
            lstFormula.Add(values);
            lstFormula.Add(this.Expression);
            object result = this.comInstance.eval(string.Join(Environment.NewLine, lstFormula));
            return Convert.ToDouble(result);
        }
        catch (Exception e)
        {
            err = string.Format("{0}", e);
            return 0;
        }
    }
}
//----- EasyCalcクラス(終了)

//----- テスト(開始)
            EasyCalc EasyCalc1 = new EasyCalc();
            EasyCalc1.Expression = "a + b + 3 + 4";
            string values = "var a = 1; var b = 2;";
            string error = string.Empty;
            double result = EasyCalc1.GetValue(values, ref error);
            Console.WriteLine("result:{0} error:{1}", result, error);

            // 使える計算式は以下のURLを参照      
            // h t t p s ://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Math
            EasyCalc1.Expression = "Math.log(1.5)";
            values = string.Empty;
            error = string.Empty;
            result = EasyCalc1.GetValue(values, ref error);
            Console.WriteLine("result:{0} error:{1}", result, error);
//----- テスト(終了)

返信 編集キー/


管理者用

- Child Tree -