【问题标题】:How to quickly cast an object in lambda in C#如何在 C# 中快速转换 lambda 中的对象
【发布时间】: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 并抛出NullReferenceExceptionas 后面应该始终跟一个 null 检查,因为 as 表示您预计转换可能会失败并且您不希望该失败引发异常。您的代码正在对其进行编码,然后继续执行,就好像不可能失败一样。

标签: c#


【解决方案1】:

这至少适用于 C# 7.1:

Button.MouseMove += (s, e) => _ = s is Drawable d ? d.Cursor = Cursors.Pointer : default;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多