Struct与赋值

    using System;
    using System.Collections.Generic;

    struct SomeStruct
    {
        public int SomeValue;
    }

    class SomeContainerClass
    {
        public SomeStruct Struct;
    }

    struct SomeContainerStruct
    {
        public SomeStruct Struct;
    }

    class Program
    {
        static void Main()
        {
            TestStruct();
            TestClass();
            TestArray();
            TestList();

            Console.ReadKey();
        }

        static SomeStruct GetDefaultValue()
        {
            return new SomeStruct { SomeValue = 100 };
        }


        private static void TestStruct()
        {
            ShowTestName("TestStruct:");
            var c = new SomeContainerStruct { Struct = GetDefaultValue() };
            ShowResult("original:", c.Struct.SomeValue);

            var s = c.Struct;
            s.SomeValue = 200;
            ShowResult("indirectly:", c.Struct.SomeValue);

            c.Struct.SomeValue = 300;
            ShowResult("directly:", c.Struct.SomeValue);
        }

        private static void TestClass()
        {
            ShowTestName("TestClass:");
            var c = new SomeContainerClass { Struct = GetDefaultValue() };
            ShowResult("original:", c.Struct.SomeValue);

            var s = c.Struct;
            s.SomeValue = 200;
            ShowResult("indirectly:", c.Struct.SomeValue);

            c.Struct.SomeValue = 300;
            ShowResult("directly:", c.Struct.SomeValue);
        }

        private static void TestArray()
        {
            ShowTestName("TestArray:");
            var c = new[] { GetDefaultValue() };
            ShowResult("original:", c[0].SomeValue);

            var s = c[0];
            s.SomeValue = 200;
            ShowResult("indirectly:", c[0].SomeValue);

            c[0].SomeValue = 300;
            ShowResult("directly:", c[0].SomeValue);
        }

        private static void TestList()
        {
            ShowTestName("TestList:");
            var c = new List<SomeStruct> { GetDefaultValue() };
            ShowResult("original:", c[0].SomeValue);

            var s = c[0];
            s.SomeValue = 200;
            ShowResult("indirectly:", c[0].SomeValue);

            //the follow line won't compile
            //Cannot modify the return value of 'System.Collections.Generic.List<StructTest.SomeStruct>.this[int]' because it is not a variable
            //c[0].SomeValue = 300;
            //ShowTestName("directly:", c[0].SomeValue);
        }


        static void ShowResult(string condition, int value)
        {
            Console.Write(condition);
            Console.Write("\t");
            Console.WriteLine(value);
        }

        static void ShowTestName(string message)
        {
            Console.WriteLine();
            Console.WriteLine(message);
        }

    }

posted on 2010-01-06 10:02  deerchao  阅读(2890)  评论(0编辑  收藏  举报