What is a good design when trying to create objects from a list of key value pairs?

So, if I have a method to parse a text file and return a list of list key values , and you want to create objects from the returned kvps (each kvps list represents a different object), what would be the best method?

The first method that comes to mind is quite simple, just save the list of keywords:

private const string NAME   = "name";
private const string PREFIX = "prefix";

and check the keys that I get for the constants I want defined above. This is pretty much the main part of the project I'm working on, so I want to do it well; Does anyone have more reliable suggestions (not to mention the fact that something is inherently irrelevant to the method described above - I'm just asking)?

Edit:

More information was requested. I work on a little game in my free time, and I create a game world with configuration files. There are four - one defines all creatures, the other defines all areas (and their locations on the map), the other defines all objects, and the latter defines various configuration parameters and things that do not fit together. With the first three configuration files, I will create objects based on the contents of the files - it will be quite heavy for the text, so there will be many lines, such as names, plurals, prefixes - that’s what. The configuration values ​​look like this:

-
key: value 
key: value
-
key: value
key: value
-

If the string '-' denotes a new section / object.

+3
source share
8 answers

XmlSerializer. XML , . :

public class DataObject {
  [Column("name")]
  public string Name { get; set; }

  [Column("prefix")]
  public string Prefix { get; set; }
}

, - , , .

+3

, , Factory, , ( - ).

private class Factory {

   public static IConfigurationObject Factory(List<string> keyValuePair) {

       switch (keyValuePair[0]) {

          case "x":
              return new x(keyValuePair[1]);
              break;
          /* etc. */
          default:
              throw new ArgumentException("Wrong parameter in the file");
       }

  }

}

, (.. (IConfigurationObject ) ).

, , . :)

EDIT: Factory , , , , . , , , .

+3

? , , ( ) . - , , , :

[java-inspired pseudo-code:]
class RestrictedKVDataStore {
   const ALLOWED_KEYS = new Collection('name', 'prefix');
   Map data = new Map();

   void put(String key, Object value) {
      if (ALLOWED_KEYS.contains(key))
          data.put(key, value)
   }

   Object get(String key) {
      return data.get(key);
   }
}
+2

, , API Reflection.Emit , .

+1

EDIT:

, , , :

List<List<KeyValuePair<String,String>>> itemConfig = 
    new List<List<KeyValuePair<String,String>>>();

- factory , /.

OLD POST:

:

:

  • Object.
  • .
  • factory .
  • KeyValuePair, , , KV.Key, KV.Value
   
      public class KeyValueToObjectFactory
      { 
         private Dictionary _kvTypes = new Dictionary();

        public KeyValueToObjectFactory()
        {
            // Preload the Types into a dictionary so we can look them up later
            // Obviously, you want to reuse the factory to minimize overhead, so don't
            // do something stupid like instantiate a new factory in a loop.

            foreach (Type type in typeof(KeyValueToObjectFactory).Assembly.GetTypes())
            {
                if (type.IsSubclassOf(typeof(KVObjectBase)))
                {
                    _kvTypes[type.Name.ToLower()] = type;
                }
            }
        }

        public KVObjectBase CreateObjectFromKV(KeyValuePair kv)
        {
            if (kv != null)
            {
                string kvName = kv.Key;

                // If the Type information is in our Dictionary, instantiate a new instance of that class.
                Type kvType;
                if (_kvTypes.TryGetValue(kvName, out kvType))
                {
                    return (KVObjectBase)Activator.CreateInstance(kvType, kv.Value);
                }
                else
                {
                    throw new ArgumentException("Unrecognized KV Pair");
                }
            }
            else
            {
                return null;
            }
        }
    }
+1

@David:
( , XML). , ; . .

@Argelbargel:
.: ')

0

... , , ...

?

.

, : .

< bb/ >

0

?

; . , .: ')

0

Source: https://habr.com/ru/post/1696730/


All Articles