【发布时间】:2022-07-07 19:14:58
【问题描述】:
我发现我必须经常施放东西。
Button.MouseMove += (s, e) =>
{
Drawable d = s as Drawable;
d.Cursor = Cursors.Pointer;
};
如何将这三行像这样减少为一行??
Button.MouseMove += (s, e) => s.Cursor = Cursors.Pointer where s as Drawable; //an example of how i want to simplify the code
【问题讨论】:
-
投吧:
((Drawable)s).Cursor = Cursors.Pointer -
这比使用
as更好(即使在两行),因为如果s不能转换为Drawable,它将抛出InvalidCastException而不是产生null并抛出NullReferenceException。as后面应该始终跟一个null检查,因为as表示您预计转换可能会失败并且您不希望该失败引发异常。您的代码正在对其进行编码,然后继续执行,就好像不可能失败一样。
标签: c#