为什么我不能对结构使用 as 关键字? [英] Why can't I use the as keyword for a struct?

查看:25
本文介绍了为什么我不能对结构使用 as 关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下结构:

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

    public Call(SourceFile caller, SourceFile callee)
    {
        this.caller = caller;
        this.callee = callee;
    }
}

后来,我把它赋给了另一个对象的 Tag 属性:

Later, I assign it to the Tag property of another object:

line.Tag = new Call(sf1, sf2);

但是当我尝试像这样检索 Tag 属性时,

But when I try to retrieve the Tag property like so,

Call call = line.Tag as Call;

Visual Studio 给出以下编译时错误:

Visual Studio gives the following compile-time error:

必须在引用类型或可为空类型

The operator as must be used within a reference type or nullable type

这是什么意思?我该如何解决?

What is the meaning of that? And how can I solve it?

推荐答案

结构体是值类型,因此不能与 as 运算符一起使用.如果转换失败,as 运算符必须能够分配一个 null 值.这仅适用于引用类型或可为空值类型.

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.

有几种方法可以解决这个问题,但最好的办法是将 Call 类型从结构更改为类.这将从本质上将您的类型从值类型更改为引用类型,这允许 as 运算符在转换失败时分配 null 值.

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.

有关值类型与引用类型的更多信息,这篇是一篇不错的文章.另外,看看MSDN:

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

这篇关于为什么我不能对结构使用 as 关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆