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

前端 未结 6 1112
囚心锁ツ
囚心锁ツ 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:18

    It's a limitation of C#. If the type were a reference type, then if the cast failed it would simply return 'null', but since it's a value type, it doesn't know what to return when the cast fails.

    You must replace your use of as with two: 'is' and 'as'

    if (line.Tag is Call) {
      call = (Call)line.Tag;
    } else {
      // Do whatever you would do if as returned null.
    }
    

提交回复
热议问题