简体   繁体   中英

Can a single class be used like this?

I have data to be stored to a file. The data is as below:

    {
       "student": {
                      "FirstName": {
                                     "Initial": "Mr.",
                                     "Value": "Luis"
                                   },
                     "MiddleName": {
                                     "Initial": "Mr.",
                                     "Value": "Bruce"
                                   },
                       "LastName": "Wayne"
                 }
    }

I retrieve the data from the file into a class Student:

     public class Student
    {
        public FirstName Firstname {get;set;}
        public MiddleName Middlename {get;set;}
        public string LastName {get;set;}
    }

    public class FirstName
   {
       public string Initial {get;set;}
       public string Value {get;set;}
   }
    public class MiddleName
   {
       public string Initial {get;set;}
       public string Value {get;set;}
   }

My question is: Can I build a class as given below to store the same info?

     public class Student
    {
        public NameClass Firstname {get;set;}
        public NameClass Middlename {get;set;}
        public string LastName {get;set;}
    }

    public class NameClass
   {
       public string Initial {get;set;}
       public string Value {get;set;}
   }

Is it the right approach? or my previous approach is better?

Don't see any problem, with that.

Actually it's definitely better, then was done before, as you unify common information in one single class.

The only thing, that comes to my mind, is that you have to revise your serialization to and from ,as you change classes architecture.

Yeah, it works pretty well...Following class structure is optimized

public class Student
 {
    public NameClass Firstname {get;set;}
    public NameClass Middlename {get;set;}
    public string LastName {get;set;}
 }

 public class NameClass
{
   public string Initial {get;set;}
   public string Value {get;set;}
}

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