4

例如,

假设 group.SupportedProducts 是 ["test", "hello", "world"]

var products = (string[]) group.SupportedProducts; 

导致“products”正确地成为包含上述 3 个元素的字符串数组 - “test”、“hello”和“world”

然而,

var products= group.SupportedProducts as string[]; 

导致产品为空。

4

1 回答 1

9

大概实际上group.SupportedProducts不是a ,但它支持自定义转换为.string[]string[]

as 从不调用自定义转换,而强制转换会。

示例来证明这一点:

using System;

class Foo
{
    private readonly string name;

    public Foo(string name)
    {
        this.name = name;
    }

    public static explicit operator string(Foo input)
    {
        return input.name;
    }
}

class Test
{
    static void Main()
    {
        dynamic foo = new Foo("name");
        Console.WriteLine("Casting: {0}", (string) foo);
        Console.WriteLine("As: {0}", foo as string);
    }
}
于 2013-02-15T23:16:39.717 回答