简体   繁体   中英

.NET Serialization getters and setters

I want to try a .NET deserialization example, but it seems I am not able to get the getters and setters working. This is my code

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace WindowsFormsApplication3

{
    [XmlRoot]
    public class TestClass
    {
        public string classname;
        private string name;
        private int age;
        [XmlAttribute]
        public string Classname { get => classname; set => classname = value; }
        [XmlElement]
        public string Name { get => name; set => name = value; }
        [XmlElement]
        public int Age { get=>age; set => age = value; }
        public override string ToString()
        {
            return base.ToString();
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            TestClass testClass = new TestClass();
            testClass.Classname = "test";
            testClass.Name = "william";
            testClass.Age = 50;
            Console.WriteLine("Hello World!");
            MessageBox.Show("Test");

        }
    }
}

And I get the following error in the get declaration: Not all code paths return a value

在此处输入图片说明

As commented by @CodeCaster, you need a minimum of C# 7.0 to work around on Expression-Bodied Members and your visual studio doesn't support it.

So you can upgrade your visual studio to C# 7.0 or use below with current version,

You can use

public string Classname
{
    get { return classname; }
    set { classname = value; }
}

instead of

public string Classname
{
    get => classname;
    set => classname = value;
}

And do the same for all other remaining properties in your class those are with expression-bodies.

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