是否有令人信服的理由反对使用 C# 关键字“as”?

发布于 2024-07-13 18:31:14 字数 292 浏览 10 评论 0原文

我发现使用以下内容:

TreeViewItem i = sender as TreeViewItem;
if(i != null){ ... }

比使用以下内容更容易编写和理解:

if(sender.GetType() == typeof(TreeViewItem)){
    TreeViewItem i = (TreeViewItem)sender;
    ...
}

是否有令人信服的理由使用第一个构造?

I find that using the following:

TreeViewItem i = sender as TreeViewItem;
if(i != null){ ... }

is easier to write and understand than:

if(sender.GetType() == typeof(TreeViewItem)){
    TreeViewItem i = (TreeViewItem)sender;
    ...
}

Are there compelling reasons not to use the first construct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

杯别 2024-07-20 18:31:15

不,我经常使用它。 它允许您以干净的方式避免 InvalidCastException 。

例如:

TreeViewItem tvItem = sender as TreeViewItem;

if (tvItem != null) return;

// Do stuff

相对于:

try
{
    TreeViewItem tvItem = (TreeViewItem)sender;
    // Do stuff.
}
catch (InvalidCastException ex)
{
    // Didn't work, do something about it
    return; // ... or not...
}

No, I use it quite a bit. It allows you to avoid InvalidCastExceptions in a clean way.

For example:

TreeViewItem tvItem = sender as TreeViewItem;

if (tvItem != null) return;

// Do stuff

as opposed to:

try
{
    TreeViewItem tvItem = (TreeViewItem)sender;
    // Do stuff.
}
catch (InvalidCastException ex)
{
    // Didn't work, do something about it
    return; // ... or not...
}
夜巴黎 2024-07-20 18:31:15

“as”更快,但要记住的是:

  • “as”返回 null 而不是抛出异常(如果这是一个问题)

  • 它不会执行自定义转换iirc

  • 它不适用于参考->值

编辑:“as”肯定更快(http://www.codeproject. com/KB/cs/csharpcasts.aspx

Edit2:所以基本上是速度与安全的决定

"as" is faster, but things to bear in mind are:

  • "as" returns a null instead of throwing an exception if that's a problem

  • it won't do custom conversions iirc

  • it doesn't work for reference->value

Edit: "as" definitely is faster (http://www.codeproject.com/KB/cs/csharpcasts.aspx)

Edit2: so basically a speed vs safety decision

哥,最终变帅啦 2024-07-20 18:31:15

如果获取错误的类型会是一个错误,那么您应该使用强制转换。 原因是确实有问题,你应该知道它。

如果该值有可能为空,并且发生这种情况时这不是系统中的错误,则使用“as”。 原因是只要可以接受空值返回,就应该使用“as”。

请记住,您不能使用“as”转换为值类型,因为它们不接受空值。 如果您有值类型并想要使用“as”,则需要使用可为空的值类型。

何时使用“as”与铸造

If getting the wrong type would be a bug, then you should use a cast. The reason for this is that there really is a problem and you should know about it.

If it is possible that the value will be null, and that is not a bug in the system when this happens then use "as". The reason being that you should use "as" any time that getting a null back is acceptable.

Keep in mind that you can't use "as" to convert to value types, because the null value is not acceptable for them. If you have a value type and want to use "as", you will need to use a nullable value type.

When to Use "as" Versus Casting

舞袖。长 2024-07-20 18:31:14

在大多数情况下,我更喜欢强制转换而不是 as ,因为通常如果对象的类型错误,则表明存在错误。 Bug应该会导致异常(IMO) - 并且执行转换的那一行的 InvalidCastException 比代码后面的 NullReferenceException 清楚得多。

当传递对您不想要的类型的对象的引用有效且合法时,应使用 as。 这种情况确实会出现,但根据我的经验,不像正常选角那么频繁。

然而,使用 GetType() 比较类型很少是正确的解决方案 - 仅当您想要检查所涉及的精确类型而不是兼容类型时,它才适用。

我写了一个明显更长的答案 关于其他地方的“演员与扮演”讨论。

I prefer casts to as in most cases because usually if the type of the object is wrong, that indicates a bug. Bugs should cause exceptions IMO - and an InvalidCastException at exactly the line which performs the cast is a lot clearer than a NullReferenceExceptionmuch later in the code.

as should be used when it's valid and legal to have been passed a reference to an object of the type that you don't want. That situation does come up, but not as often as normal casting in my experience.

Comparing types using GetType(), however, is very rarely the right solution - it's only appropriate when you want to check for the exact type involved rather than a compatible type.

I've written a significantly longer answer about the "cast vs as" discussion elsewhere.

顾忌 2024-07-20 18:31:14

完全不是——它让您有机会验证转换(转换)是否完成正常。 如果这样做,

TreeViewItem i = (TreeViewItem) sender;

如果转换失败,您可能会遇到异常。

Not at all - it gives you the chance to verify that the conversion (cast) was done OK. If you do

TreeViewItem i = (TreeViewItem) sender;

you might get an exception if the cast fails.

全部不再 2024-07-20 18:31:14

一般来说,这两个片段是等价的。 即使 senderTreeViewItem 的孙子,TreeViewItem i = sender as TreeViewItem 也会产生正确的结果,而 sender .GetType() == typeof(TreeViewItem) 将为 true sender 恰好为 TreeViewItem 时> 及其任何可能的子类。

Generally speaking, these two snippets are not equivalent. TreeViewItem i = sender as TreeViewItem will yield a correct result even if sender is a grand-grand-child of TreeViewItem, whereas sender.GetType() == typeof(TreeViewItem) will be true only when sender is precisely TreeViewItem and none of its possible subclasses.

幽梦紫曦~ 2024-07-20 18:31:14

“如”:好东西。 一直使用它。

如果您确实想要手动比较类型的替代方法,请尝试:

  if(person is Employee) { }

读起来更好。

"as": good stuff. use it all the time.

if you really want an alternative to manually comparing types try:

  if(person is Employee) { }

reads better yet.

飘逸的'云 2024-07-20 18:31:14

您的示例最好写为:

if (sender is TreeViewItem) {
    TreeViewItem i = (TreeViewItem)sender;
    ...
}

as 运算符可以帮助避免这种双重类型检查。 所以对于你引用的例子,我想说这绝对是一个很好的解决方案。

然而,在某些情况下,您确实确实想要演员阵容。 如果您需要一个 TreeViewItem 并且不需要其他任何东西,那么转换将确保在您获得其他任何东西时抛出 InvalidCastException

就像在大多数情况下一样,这里没有一揽子规则:使用正确的工具完成正确的工作

Your example would be better written as:

if (sender is TreeViewItem) {
    TreeViewItem i = (TreeViewItem)sender;
    ...
}

It is exactly this dual type checking that the as operator can help avoid. So for your cited example, I would say it is definitely a good solution.

However, there are situations where you really do want a cast. If you're expecting a TreeViewItem and want nothing else, casting will ensure an InvalidCastException is thrown if you're given anything else.

Just like in most situations, there is no blanket rule here: use the right tool for the right job.

独自←快乐 2024-07-20 18:31:14

如果您想要一个普通(不可为空)值类型,显然这不起作用,例如:

int test = sender as int;

无效,但是:

int? test = sender as int?;

是允许的。

If you want a plain (not nullable) value type, obviously this won't work, eg:

int test = sender as int;

isn't valid, however:

int? test = sender as int?;

is allowed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文