简体   繁体   中英

How is a struct defined as a property?

The title may be incorrect, if so please change. I'm not sure how to ask my question so just look at the code as it should be obvious.

Using the commented code will work but I want to know why the actual code does not work. I'm sure it's wrong but how can it be fixed? Or is this not how its done?

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();
        }
    }
}

A struct is copied only by value, so all you wind up doing is changing the copy that was returned. Use a class.

Use

Foo.FooBar myFooBar = new Foo.FooBar { Baz = 1 };
f.Bar = myFooBar;

Like Steven said, you need to create an instance of a struct, and set the property to it. Otherwise it is passed by value.

Also, you can think of the struct as "already allocated", so you don't need too new() it. Instead of

this.Bar = new FooBar();

Just do

this.Bar.Baz = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM