Why can't I use the as keyword for a struct?

前端 未结 6 1103
囚心锁ツ
囚心锁ツ 2020-12-11 14:21

I defined the following struct:

public struct Call
{
    public SourceFile caller;
    public SourceFile callee;

    public Call(SourceFile caller, SourceFi         


        
6条回答
  •  既然无缘
    2020-12-11 15:16

    A struct is a value type, so it cannot be used with the as operator. The as operator must be able to assign a value of null if the cast fails. This is only possible with a reference type or a nullable value type.

    There are a couple ways to solve this, but your best bet is to change your Call type from a struct to a class. This will essentially change your type from a value type to a reference type, which allows the as operator to assign a value of null if the cast fails.

    For more information on value types vs. reference types, this is a decent article. Also, have a look on MSDN:

    • value types
    • reference types
    • as-operator
    • nullable types.

提交回复
热议问题