当你应该使用的关键字在C#当你、关键字

2023-09-03 05:16:41 作者:你快滚,趁我没说舍不得

当你想改变的类型大部分的时间你只是想用传统的铸造。

When you want to change types most of the time you just want to use the traditional cast.

var value = (string)dictionary[key];

这是很好的,因为:

It's good because:

在它的快速 它会抱怨,如果事情是错的(而不是给对象是空的例外)

那么,什么是一个很好的例子,使用我真的无法找到或想到的是完全适合自己的东西吗?

So what is a good example for the use of as I couldn't really find or think of something that suits it perfectly?

注:其实我觉得有时候有一些情况下的编译器prevents采用铸造,其中作品(仿制药有关?)

Note: Actually I think sometimes there are cases where the complier prevents the use of a cast where as works (generics related?).

推荐答案

使用时,它的有效的一个对象不能是的键入你想要的,你要采取不同的行动,如果它是。例如,在有些伪code:

Use as when it's valid for an object not to be of the type that you want, and you want to act differently if it is. For example, in somewhat pseudo-code:

foreach (Control control in foo)
{
    // Do something with every control...

    ContainerControl container = control as ContainerControl;
    if (container != null)
    {
        ApplyToChildren(container);
    }
}

或者优化LINQ到对象(大量的例子是这样):

Or optimization in LINQ to Objects (lots of examples like this):

public static int Count<T>(this IEnumerable<T> source)
{
    IList list = source as IList;
    if (list != null)
    {
        return list.Count;
    }
    IList<T> genericList = source as IList<T>;
    if (genericList != null)
    {
        return genericList.Count;
    }

    // Okay, we'll do things the slow way...
    int result = 0;
    using (var iterator = source.GetEnumerator())
    {
        while (iterator.MoveNext())
        {
            result++;
        }
    }
    return result;
}

因此​​,使用就像一个 +一个演员。它的总是的使用了无效检查后,按照上面的例子。

So using as is like an is + a cast. It's almost always used with a nullity check afterwards, as per the above examples.