[英]Convert string containing bool condition to bool (C#)
I would like to convert (but i think it's not possible) a string into a bool, in this way:我想以这种方式将(但我认为这是不可能的)字符串转换为布尔值:
string a = "b.Contains('!')";
private void print(string condition)
{
string b = "Have a nice day!";
/* Some kind of conversion here for condition parameter */
/* like bool.Parse(condition) or Bool.Convert(condition) */
if(condition)
{
Console.Write("String contains !-character.");
}
}
Mind that the bool-string has to be passed to the function as a parameter.请注意,必须将布尔字符串作为参数传递给 function。
Is there a way to achieve this?有没有办法做到这一点?
I think you need to use an auxiliar bool variable, like this example..我认为您需要使用辅助 bool 变量,例如此示例..
bool aux = false;
private bool print(string condition)
{
string b = "Have a nice day!";
if(b.Contains(condition))
aux = true;
return aux;
}
Or the same example without auxiliar.或者没有辅助的同一个例子。
private bool print(string condition)
{
string b = "Have a nice day!";
return b.Contains(condition);
}
Then call the method print to check if it is true or false and write the message you want然后调用方法 print 来检查是真还是假并写出你想要的消息
if(print("!"))
Console.WriteLine("String contains !-character.");
There is no built in way to parse your string to a expression.没有内置方法可以将您的字符串解析为表达式。
But of your goal is to sent the expression to an other function you could do this但是你的目标是将表达式发送到另一个 function 你可以这样做
using System;
public class Program
{
public static void Main()
{
print(x=>x.Contains("!"));
}
private static void print(Func<string,bool> condition)
{
string b = "Have a nice day!";
/* Some kind of conversion here for condition parameter */
/* like bool.Parse(condition) or Bool.Convert(condition) */
if(condition.Invoke(b))
{
Console.Write("String contains !-character.");
}
}
}
if you would like a non build in way you could look at: Is there a tool for parsing a string to create a C# func?如果您想要一种非构建方式,您可以查看: Is there a tool for parsing a string to create a C# func?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.