我需要创建一个看起来像int的结构(但是我需要一个额外的字段......),所以我创建了一个名为TestStruct的新结构,添加了一个我需要的方法(test())并重载了一些运算符,它看起来运作良好......
下面的示例显示了问题.如果从Val属性执行结构test()方法,那么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(); …Run Code Online (Sandbox Code Playgroud)