c# - 如何检查 Button.Tag 的首字母?

标签 c#

所以我在我的代码中订购了带有标签的按钮,标签的第一个字母决定它是一组按钮还是另一组按钮。 我需要检查按钮是否在一组或另一组中,我正在尝试检查标签的第一个字母,就像普通字符串一样 ((Button)sender).Tag[0] == 'W'((Button)sender).Tag.FirstOrDefault() == 'W' 但是代码给我一个错误。我错过了什么?

最佳答案

在 WPF 和 Winforms 中,Tag 都被声明为 object。因此,您需要将其转换为字符串:

var button = ((Button)sender);
var tagString = (string)button.Tag;
if (tagString[0] == 'W') ...

如果您不确定标签是否始终是字符串,您可以使用 as-cast:

var button = ((Button)sender);
var tagString = button.Tag as string;
if (tagString != null && tagString[0] == 'W') ...

或者对于 C# 7,您还可以使用模式匹配:

var button = ((Button)sender);
if (button.Tag is string tagString && tagString[0] == 'W') ...

关于c# - 如何检查 Button.Tag 的首字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55480764/

相关文章:

c# - Roslyn 功能/模式分支 (C# 7) - 如何启用实验性语言功能

c# - 使用 C# 使用 Windows 服务 [用 C# 编写]

c# - 使用 Ajax 自动完成

c# - Excel VSTO -> Hide/Unhide Ribbon Button based on another Ribbon Button 单击

c# - 使用 C# 如何检测是否安装了 Windows Installer 4.5

c# - 用希伯来字母反序列化json

c# - 像 Web.Application 中的功能一样绘制?

c# - 从 "run as"凭据下运行的进程获取登录用户名

c# - 在 for 循环中随机生成一个 int 值。 7 次迭代后,它返回一个非常大的负数。为什么是这样?

c# - 如何知道为什么我的 WPF 窗口这么大?