使用expansion method 實作 EValue 與解決 x86 與 x64 的衝突

摘要:使用expansion method 實作 EValue 與解決 x86 與 x64 的衝突

  前一陣子由於專案需要,做了一個Utility是專門用來做文字運算,也就是如果你有一個字串資料值為 "100*200" 呼叫完Utility他會幫你計算成 20000 的資料回傳給你,在SQL裡面可以很輕易的做到這個需求,但是在.NET中確是缺乏了這個Method,我使用的方式是利用LINQ提供的外掛型 Method ,方法如下Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Utility {

    /// <summary>實現EVAL()的Method</summary>
    public static class EValue {

        private static MSScriptControl.ScriptControlClass ScriptControl;

        public static double EVal(this string paramFormula) {
            double ReturnValue = 0;

            if (paramFormula.Trim() == "") return 0;

            //初始化Script Control
            EValue.InitiationScriptControl();
            //Reset Script Control
            ScriptControl.Reset();
            try {
                ReturnValue = double.Parse(ScriptControl.Eval(paramFormula).ToString());
            } catch (Exception) {
                ReturnValue = 0;
            }
            return ReturnValue;
        }

        private static void InitiationScriptControl() {
            if (ScriptControl == null) {
                ScriptControl = new MSScriptControl.ScriptControlClass();
                ScriptControl.Language = "VBScript";
                ScriptControl.AllowUI = false;
            }
        }

    }
}

  然而使用這個 Utility 必須要加入 Interop.MSScriptControl.dll 這元件,使用的方法就是將它(EValue) Using 進來,Using 進來後所有的 String 就可以擁有 EValue 這功能如下程式:

Using Utility;
namespace TestEvalue {

    /// <summary>實現EVAL()的Method</summary>
    public class TestEvalue {

        public void Main() {

            string FormulaValue = "100*15*1250/2.5";

            try {
                MessageBox.Show(FormulaValue.EValue().ToString());
            } catch (Exception) {
                ReturnValue = 0;
            }
            return ReturnValue;
        }

    }
}

  如此就會出現如750000的MessageBox,如下圖1.1


圖1.1

  該篇文章主要要表現的不是上述的這個Method,而是在使用上幾乎都正常,確有例外的狀況。就是遇到當我在呼叫的時候出現下列的這個錯誤訊息:

COM class factory for component with CLSID {0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC} failed due to the following error: 80040154.

  查了一下發現這居然是x86與x64的問題,解決方法就是在專案處點選右鍵選擇 Properties 如圖1.2


圖1.2

  在屬性視窗中,可以找到 Build 的頁籤,在 Build 的頁籤中可以找到 Platform target = x86,如圖1.3


圖1.3