![](/img/trans.png)
[英]Casting and As operator resulting in the casted object and a null reference respectively
[英]Why does casting using “as” operator result in the casted object being null with C# dynamics
例如,
讓我們說group.SupportedProducts是[“test”,“hello”,“world”]
var products = (string[]) group.SupportedProducts;
導致“products”正確地成為一個包含上述3個元素的字符串數組 - “test”,“hello”和“world”
然而,
var products= group.SupportedProducts as string[];
導致產品為空。
推測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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.