直接访问结构内部值

Directly accessing struct inner value

不确定如何表达或搜索它,因为我缺少 "real name"。

C#中的某些结构体可以直接作为其包含类型,例如Nullable<>,一个Nullable可以直接当作一个int,例如:

Nullable<int> ex;

void Example(){
    ex += 1;
}

我现在的问题是在我自己的结构中实现这种行为,例如我可以创建一个 Savable 并且仍然能够像在 nullable 中那样像普通 int 一样对待变量?而不是做 mySavable.value,例如

希望我的问题足够清楚,这无疑是一个重复的问题,但我在搜索中找不到另一个问题,因为我缺少这个 "technique" 的正确名称。对此深表歉意!

非常感谢!

看看here。您会注意到 Nullable 重载了隐式转换运算符。这就是 T 可以隐式转换为 Nullable 的原因。如果您需要其他运算符,则必须在 class.

中重载它们

Nullable<> 类型是一个坏例子。它受编译器支持,并且具有其他人无法做到的魔力。

您可以定义一些 implicit/explicit 转换运算符,这将隐式或显式转换 YourStruct <-> int,或者您可以定义一些接受的运算符,例如 YourStruct + int。两种解决方案都将解决您的问题。请注意,要获得 += 运算符,您只需要定义 + 运算符即 returns 和 YourStruct(或定义隐式转换 int -> YourStruct)。

例如,重载 operator+(Example1, Example1) 和重载隐式转换 from/to int 您可以:

public struct Example1
{
    public readonly int Value;

    public Example1(int value)
    {
        this.Value = value;
    }

    public static Example1 operator +(Example1 t1, Example1 t2)
    {
        return new Example1(t1.Value + t2.Value);
    }

    // This is used only for the "int v1 = e1;" row
    public static implicit operator int(Example1 value)
    {
        return value.Value;
    }

    public static implicit operator Example1(int value)
    {
        return new Example1(value);
    }
}

然后

Example1 e1 = 1;
Example1 e2 = 2;
Example1 sum1 = e1 + e2;
Example1 sum2 = e1 + 4;
Example1 sum3 = 4 + e1;
sum3 += sum1;
sum3 += 1;
int v1 = e1;

或者您可以简单地重载 Example2int 之间的各种 operator+:

public struct Example2
{
    public readonly int Value;

    public Example2(int value)
    {
        this.Value = value;
    }

    public static Example2 operator +(Example2 t1, Example2 t2)
    {
        return new Example2(t1.Value + t2.Value);
    }

    public static Example2 operator +(Example2 t1, int t2)
    {
        return new Example2(t1.Value + t2);
    }

    public static Example2 operator +(int t1, Example2 t2)
    {
        return new Example2(t1 + t2.Value);
    }
}

然后

Example2 e1 = new Example2(1);
Example2 e2 = new Example2(2);
Example2 sum1 = e1 + e2;
Example2 sum2 = e1 + 4;
Example2 sum3 = 4 + e1;
sum3 += sum1;
sum3 += 1;
int v1 = e1.Value;

(注意 operator+ 不可交换,所以我必须同时定义 Example2 + intint + Example2