Overriding the Defaults in a struct (c#)

前端 未结 12 941
感情败类
感情败类 2021-01-04 00:47

Is it possible to set or override the default state for a structure?

As an example I have an

enum something{a,b,c,d,e};

and a struc

12条回答
  •  走了就别回头了
    2021-01-04 01:29

    this should work

    public struct MyStruct 
    {
        private string myName;
        private int? myNumber;
        private bool? myBoolean;
        private MyRefType myType;
    
        public string MyName
        {
            get { return myName ?? "Default name"; }
            set { myName= value; }
        }
        public int MyNumber
        {
            get { return myNumber ?? 42; }
            set { myNumber = value; }
        }
        public bool MyBoolean
        {
            get { return myBoolean ?? true; }
            set { myBoolean = value; }
        }
        public MyRefType MyType 
        {
            get { return myType ?? new MyRefType(); }
            set { myType = value; }
        }
    
        //optional
        public MyStruct(string myName = "Default name", int myNumber = 42, bool myBoolean = true)
        {
            this.myType = new MyRefType();
            this.myName = myName;
            this.myNumber = myNumber;
            this.myBoolean = myBoolean;
        }
    }
    

    [TestClass]
    public class MyStructTest
    {
        [TestMethod]
        public void TestMyStruct()
        {
            var myStruct = default(MyStruct);
            Assert.AreEqual("Default name", myStruct.MyName);
            Assert.AreEqual(42, myStruct.MyNumber);
            Assert.AreEqual(true, myStruct.MyBoolean);
            Assert.IsNotNull(myStruct.MyType);
        }
    }
    

提交回复
热议问题