2015-10-29 24 views
-2

enter image description here在如果條件C#返回變量值

我理想如果條件一樣 如果(20> 13 & 18).....

+0

請說清楚你的意思。此外,請包括*代碼*,而不是代碼的屏幕截圖。 – Rob

+0

如果你在這裏粘貼你的代碼而不是顯示它的圖片,那將是非常棒的。 –

+0

首先和最重要的20將永遠不會少於18 ...哪個值是您的變量? – Ben

回答

1

有兩種方式(很多方式,但我更喜歡這些)。

慢速方式:(真的很慢)使用CodeDom在運行時編譯字符串。示例:

using System.CodeDom.Compiler; 
using Microsoft.CSharp; 

//... 

private static void Main() 
{ 
    string Tempreture = "20 > 13 && 20 < 18"; 
    bool? result = Evaluate(Tempreture); 
    if (!result.HasValue) 
    { 
     throw new ApplicationException("invalid expression."); 
    } 
    else if (result.Value) 
    { 
     //... 
    } 
    else 
    { 
     //... 
    } 
} 

public static bool Evaluate(string condition) 
{ 
    // code to compile. 
    const string conditionCode = "namespace Condition {{public class Program{{public static bool Main(){{ return {0};}}}}}}"; 

    // compile code. 
    var cr = new CSharpCodeProvider().CompileAssemblyFromSource(
     new CompilerParameters { GenerateInMemory = true }, string.Format(conditionCode, condition)); 

    if (cr.Errors.HasErrors) return null; 

    // get the method and invoke. 
    var method = cr.CompiledAssembly.GetType("Condition.Program").GetMethod("Main"); 
    return (bool)method.Invoke(null, null); 
} 

快速的方法:使用Ncalc庫動態解析表達式。

using NCalc; 

// ... 

string Tempreture = "20 > 13 && 20 < 18"; 
NCalc.Expression e = new Expression(Tempreture); 
if (e.HasErrors()) 
{ 
    throw new ApplicationException("invalid expression"); 
} 
if ((bool)e.Evaluate()) 
{ 
    //... 
} 
else 
{ 
    //... 
} 
+0

謝謝.......它正在工作 –

+0

請告訴我另一種方法做到這一點 –

+0

@ImranPathan你能告訴我什麼是問題用這兩種方式?如果你在某處告訴我所以我可以幫你修復它。 –

0

我假定x = 20

使用這個變量值

然後,你可以這樣做:

if(x > 13 && x <18) 
+0

20> 13 && 20 <18這個值來自數據庫,因爲它是我要放在if條件,如果如果(20> 13 && 20 <18) –

+0

哦。所以你想評估表達。你可以使用CSharpCodeProvider,但你需要在裏面創建一個適當的類和eval方法 – Umesh