例如,
让我们说group.SupportedProducts是[“test”,“hello”,“world”]
var products = (string[]) group.SupportedProducts;
导致“products”正确地成为包含上述3个元素的字符串数组 - “test”,“hello”和“world”
然而,
var products= group.SupportedProducts as string[];
导致产品为空。
答案 0 :(得分:9)
大概group.SupportedProducts
实际上 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);
}
}