为什么我不能用作为关键字的结构?我不、能用、关键字、结构

2023-09-04 07:02:59 作者:真心算个屁

我定义了以下结构:

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.