代码之家  ›  专栏  ›  技术社区  ›  Fake Code Monkey Rashid

如何将结构定义为属性?

  •  1
  • Fake Code Monkey Rashid  · 技术社区  · 17 年前

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

    使用注释过的代码可以工作,但是我想知道为什么实际的代码不能工作。我敢肯定这是错的,但怎么能解决呢?还是不是这样的?

    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();
            }
        }
    }
    
    3 回复  |  直到 17 年前
        1
  •  9
  •   Steven Sudit    17 年前

    结构仅按值复制,因此您所要做的就是更改返回的副本。使用一个类。

        2
  •  5
  •   Yuriy Faktorovich    17 年前

    使用

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

    正如Steven所说,您需要创建一个结构实例,并将属性设置为它。否则按值传递。

        3
  •  1
  •   Ray    17 年前

    此外,您可以将该结构视为“已分配”,因此不需要太新的()结构。而不是

    this.Bar = new FooBar();
    

    照办

    this.Bar.Baz = 1;