gpt4 book ai didi

如果属性访问 C# Struct 方法不保存值

转载 作者:行者123 更新时间:2023-11-30 13:10:39 24 4
gpt4 key购买 nike

我需要创建一个看起来像 int 的结构(但有一个我需要的额外字段...),所以我创建了一个名为 TestStruct 的新结构,添加了一个我需要的方法 (test()) 并重载了一些运营商,它似乎运作良好......

下面的示例显示了问题。如果结构 test() 方法是从 Val 属性执行的,那么 Val 属性似乎丢失了值,但是如果该方法是在 Val2 变量上执行的,这个方法似乎保留了正确的值...

为什么会这样?

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
new TestClass();
}
}

public class TestClass
{
public TestStruct Val { get; set; }
private TestStruct Val2;

public TestClass()
{
Val.test();
Console.WriteLine(Val + "-> why is it not 10?");

//Direct assignment works well...
Val = 123;
Console.WriteLine(Val + "-> direct assingment works..");

//This way works too. Why doesn't it work with "get;" and "set;"?
Val2.test();
Console.WriteLine(Val2 + "-> it works this way");
}
}

public struct TestStruct
{
private Int32 _Value;
public long Offset { get; set; }

public static implicit operator TestStruct(Int32 value)
{
return new TestStruct { _Value = value };
}

public static implicit operator Int32(TestStruct value)
{
return value._Value;
}

public void test()
{
_Value = 10;
}
}

最佳答案

你的结构是错误的。

出于很多原因,您永远不要创建可变结构。

就像 intDateTime 值是不可变的,永远不会改变一样,struct 的特定值也绝不能改变全部。

相反,您可以创建返回新的不同值的函数。

以下是可变结构是邪恶的一些原因:

  1. http://ericlippert.com/2008/05/14/mutating-readonly-structs/
  2. http://blog.slaks.net/2010/12/when-shouldnt-you-write-ref-this.html
  3. http://codeblog.jonskeet.uk/2010/07/27/iterate-damn-you/
  4. http://philosopherdeveloper.wordpress.com/2011/03/31/how-i-discovered-a-bug-in-the-c-compiler-part-1/

要回答这个问题,Val.test() 等同于 get_Val().test()
由于结构是值类型,`get_Val()(自动生成的属性 getter )返回结构的副本
私有(private)支持字段中的原始结构不受影响。

关于如果属性访问 C# Struct 方法不保存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6770604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com