转换为自定义类类型

时间:2018-06-03 18:01:29

标签: c# .net

我正在尝试将与按钮的“Tag”属性一起传递的字符串值转换为自定义类型“DialogClosingEventArgs”,如下所示:

var converted = (DialogClosingEventArgs)((Button)sender).Tag;

但是在运行时我遇到以下异常:“无法将'System.String'类型的对象强制转换为'MaterialDesignThemes.Wpf.DialogClosingEventArgs'

如何强制进行转换?

1 个答案:

答案 0 :(得分:0)

要将对象强制转换为类型,它必须与您投射的类型兼容。正如你所说,这是一个string,因此它不能转换为DialogClosingEventArgs

使用:

button.Tag = 3;
int a = (int)button.Tag;

不起作用:

button.Tag = "some string";
int a = (int)button.Tag;

因为string不能转换为int。

相关问题