C# 在C中的文本块上执行If语句#
问题:C# 在C中的文本块上执行If语句#,c#,if-statement,textblock,C#,If Statement,Textblock,问题: if (string content.contains("Chocolate")); { Uri Pure = new Uri("Images/ChocolatePortrait.png", UriKind.Relative); BitmapImage imageSource = new BitmapImage(Pure); image2.Source = imageSource;
if (string content.contains("Chocolate"));
{
Uri Pure = new Uri("Images/ChocolatePortrait.png", UriKind.Relative);
BitmapImage imageSource = new BitmapImage(Pure);
image2.Source = imageSource;
}
试图从本质上说,如果我的文本块包含“X”,然后执行IF,但我不知道如何在正确的上下文中编写它
示例:
如果文本块中有“Chocolate”一词,我想显示“Chocolate”的图像(我已经知道如何正确显示图像,我的问题在于If语句本身)
我对这类东西还不熟悉,我想知道,以备将来参考
问题:
if (string content.contains("Chocolate"));
{
Uri Pure = new Uri("Images/ChocolatePortrait.png", UriKind.Relative);
BitmapImage imageSource = new BitmapImage(Pure);
image2.Source = imageSource;
}
现在,我不知道如何以实际工作的方式对文本块/字符串执行IF语句
尝试:
if (string content.contains("Chocolate"));
{
Uri Pure = new Uri("Images/ChocolatePortrait.png", UriKind.Relative);
BitmapImage imageSource = new BitmapImage(Pure);
image2.Source = imageSource;
}
使用==测试是否相等
if (textBlock.Text == "Chocolate")
{
Uri Pure = new Uri("Images/ChocolatePortrait.png", UriKind.Relative);
BitmapImage imageSource = new BitmapImage(Pure);
image2.Source = imageSource;
}
你也可以这样做:
if (textBlock.Text.Contains("Chocolate", StringComparison.OrdinalIgnoreCase))
{
// ....
}
如果您在文本块的文本中查找“chocolate”一词,并且不希望检查区分大小写。您可以检查是否与以下内容相等:
if (textBlock.text.Equals("Chocolate");
{
//do whatever must be done here
}
或者您也可以使用==(这样您就不需要在之前检查null)。
但是,对于“Equals”,您也可以使用重载函数,例如忽略大小写。问题是您过早地用分号终止if语句
代码>
if (textBlock.Text.Contains("Chocolate")) // <= removed the ";"
{
Uri Pure = new Uri("Images/ElfPortrait.png", UriKind.Relative);
BitmapImage imageSource = new BitmapImage(Pure);
image2.Source = imageSource;
}
请注意,“巧克力很好!”。包含(“巧克力”)
返回true
。如果整个字符串必须等于单词,则与textBlock.Text==“Chocolate”
在google中查找“字符串比较c”。一开始可能会很棘手。但他不想检查是否相等,或者至少听起来是这样。请注意,textBlock是textBlock的一个糟糕名称。如果他真的在使用类名,那将不起作用,需要更改为实际的实例名。我在他的帖子中读到他想检查是否相等,比如他说,“如果文本块中有“巧克力”一词,我想……”如果文本为空,这将引发异常。还要注意,=
操作符重载字符串,以执行字符串值的比较,而不是它的引用。使用==
会更好,而不是更差。谢谢,这很有效!我觉得自己像个白痴。我也会接受这个答案。其工作方式是文本永远不会为空,用户需要单击一个按钮,该按钮填充文本块中的文本。听起来很愚蠢,我知道。但我是一个相对较新的程序员(几个月前才从VB跳出来)@Servy我坚信,==在后台也做同样的事情。此外,textBlock.text永远不会为null,除非将其设置为null。此外,还可以使用Equals的重载。当然,您也可以使用==来比较两个字符串。@Servy但是,我编辑了我的答案,因为它听起来太像“而不是使用等于而不是==”。我认为这也是一个意见问题。@FabianBigler你特意建议使用Equals
而不是=
。这意味着==
在某种程度上是不合适的。事实并非如此。
if(YOUR_STRING_HERE.Contains(STRING_YOU_WANT_TO_FIND))
{
//do your stuff here
}