问题
I have to convert a string to bool and evaluate the string condition. For example:
string condition = "8 > 9 || !8";
then the condition has to evaluate and return true;
if string condition = "!8"; then condition has to return true.
Suggest me how to evaluate the condition.
回答1:
Generally, if you want to evaluate C# code during runtime, you can use the .NET Compiler Platform (Roslyn) via the Microsoft.CodeAnalysis.CSharp.Scripting Nuget package.
BTW, I found this right here in stack overflow: How can I evaluate a C# expression dynamically?
here's a solution to your specific requirement, assuming the only exception to valid C# expressions is treating !8 as boolean true (specifically "!8" preceded or followed followed by any other character is forbidden).
private async Task<bool> ProcessExpression(string expression)
{
var processedExpression = expression.Replace("!8", "true");
return await CSharpScript.EvaluateAsync<bool>(processedExpression);
}
And here's some test code for the above:
Task.Run(async () =>
{
var expresion = "8 > 9";
var result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
expresion = "8 < 9";
result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
expresion = "!8";
result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
expresion = "8 > 9 || !8";
result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
expresion = "8 > 9 && !8";
result = await ProcessExpression(expresion);
Console.WriteLine($"{expresion} : {result}");
});
The output we get is:
8 > 9 : False 8 < 9 : True !8 : True 8 > 9 || !8 : True 8 > 9 && !8 : False
please note that this solution has a performance penalty and if this is a concert than you should look for other options such as writing a dedicated parser or look for 3rd party Nuget packages.
回答2:
Try using the IValueConverter interface provided by .net
https://docs.microsoft.com/en-us/dotnet/api/system.windows.data.ivalueconverter?view=netframework-4.8
Where u define 2 methods Convert and ConvertBack Each method takes a parameter of type object and return the type object
so u can input the string and return the Boolean. As for the conversion from a string to expression you can checkout this link https://expressiontree-tutorial.net/knowledge-base/5029699/csharp-convert-string-expression-to-a-boolean-expression which have the required code cleared out.
来源:https://stackoverflow.com/questions/60261488/how-to-convert-string-to-bool-and-evaluate-the-condition