c# - 为什么 C# Struct 的行为与属性不同?(与声明为字段相比)
问题描述
我理解 struct 是值类型。但我不明白为什么它会这样?是因为我没有将其视为不可变的吗?还是与 auto 属性有关?
using System;
namespace StructQuestion
{
class Program
{
static StructType structAsProperty { get; set; }
static StructType structAsField;
static void Main(string[] args)
{
structAsProperty.InjectValue("structAsProperty");
structAsField.InjectValue("structAsField");
//debugger says structAsProperty.GetValue() is null
Console.WriteLine(structAsProperty.GetValue());
Console.WriteLine(structAsField.GetValue());
Console.ReadLine();
}
}
public struct StructType
{
private string value;
public void InjectValue(string _value)
{
value = _value;
}
public string GetValue()
{
return value;
}
}
}
解决方案
让我们看看这个语句中发生了什么:
structAsProperty.InjectValue("structAsProperty");
我们不必走太远。必须发生的第一件事是解决structAsProperty
语句的一部分。这里的关键是理解编译器将属性get
和set
部分重写为幕后的方法调用。
所以我们在这里真正拥有的是对返回结构值的方法的调用。我在这里说“值”而不是“对象”,因为结构是值类型。对于值类型,传递给方法或从方法返回会产生值的副本。
现在我们已经足够了解发生了什么。我们调用InjectValue()
的是属性结构的副本,而不是属性本身的实例。接下来我们通过它的方法修改这个副本InjectValue()
……然后立即忘记这个副本曾经存在过。
你可以像这样修复它:
var prop = structAsProperty; //now we have a variable to keep the result of the implicit get accessor method
prop.InjectValue("structAsProperty");
structAsProperty = prop;
推荐阅读
- unix - 如何使用 awk 替换二进制文件中的单个字节
- android - 对设备中的文档(.pdf、.doc、.xlsx)进行本机搜索
- amazon-web-services - AWS Glue - 条件触发器是否可以根据另一个工作流程中的作业条件触发?
- javascript - 动画 CSS 不随页面漫步
- excel - 数据工厂中具有多行列标题和空白列的 Excel 文件?
- reactjs - 如何使用 Next.js 访问当前在导航中加载的 url 或页面
- cypress - cypress.io:登录功能不起作用
- kubernetes - Velero 备份在 aks 中失败
- c# - 如何无限生成统一的网格?
- r - 使用函数创建新变量时出错,R中的变量之间有减法