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

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

问题描述

我定义了以下结构:

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?

推荐答案

一个结构是值类型,所以它不能与作为运营商。该运营商必须能够如果转换失败分配空值。这是唯一可能与引用类型或可空类型。

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.

有几种方法可以解决这个问题,但最好的办法是改变你的呼叫从结构类类型。这将主要从值类型为引用类型,它允许运营商,如果转换失败分配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:

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

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

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