如何将结构定义为属性?

Fak*_*hid 1 c# struct properties

标题可能不正确,如果是,请更改.我不知道如何提出我的问题,所以只看代码,因为它应该是显而易见的.

使用注释代码将起作用,但我想知道为什么实际代码不起作用.我确定这是错的,但如何解决呢?或者这不是它的完成方式吗?

using System;

namespace SomethingAwful.TestCases.Structs
{
    public class Program
    {
        public static void Main()
        {
            Foo f = new Foo();
            f.Bar.Baz = 1;

            Console.WriteLine(f.Bar.Baz);
        }
    }

    public class Foo
    {
        public struct FooBar
        {
            private int baz;

            public int Baz
            {
                get
                {
                    return baz;
                }
                set
                {
                    baz = value;
                }
            }

            public FooBar(int baz)
            {
                this.baz = baz;
            }
        }

        private FooBar bar;

        public FooBar Bar
        {
            get
            {
                return bar;
            }
            set
            {
                bar = value;
            }
        }

        //public FooBar Bar;

        public Foo()
        {
            this.bar = new FooBar();
            //this.Bar = new FooBar();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*dit 9

结构仅按值复制,因此您最后要做的就是更改返回的副本.使用课程.


Yur*_*ich 5

使用

Foo.FooBar myFooBar = new Foo.FooBar { Baz = 1 };
f.Bar = myFooBar;
Run Code Online (Sandbox Code Playgroud)

就像Steven所说,你需要创建一个struct的实例,并将属性设置为它.否则它按值传递.