C # a new class with a single property: get from the database or encapsulate in a new one?

I tried to describe :) This is more a programming style problem than a coding problem itself.

Suppose we have:

AND:

public class MyDict {
     public Dictionary<int,string> dict;
     // do custom-serialization of "dict"
     public void SaveToFile(...);
     // customized deserialization of "dict"
     public void LoadFromFile(...);
} 

AT:

public class MyDict : Dictionary<int,string>
{

}

Which option would be better in terms of programming style? class B: must be / serialized outside.

The main problem is this: is it better to create a new class (which will have only one property - for example, select A :) or create a new derived class, for example opt B :? I do not want any other data processing than adding / removing and de-serializing for a stream.

Thanks in advance!

+3
source share
7 answers

? , , ? :

public void SaveDictionary(Dictionary<int, string> dictionary, string fie)

public Dictionary<int, string> LoadDictionary(string file)
+6

B. , (.. /) .

, , , (a la Option B)

+1

:

"" / API , . "", , .

: . , . , , push_back, push_front, removeAt, . .

, , -, "" . , , , :

class DictionarySerializationHelper
{
    public static void Serialize(Dictionary<int, String> d, File f){
    //...
    }
    public static Dictionary<int, String> Deserialize(File f)
    {
    //...
    }
}

, , .

+1

2 :

A - , , .

B - , , ,

, , / , , , ...

.

.

+1

public static class DictionaryExtensions
{
    public static void Save<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string fileName)
    {
        // TODO: save logic
    }

    public static void Load<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string fileName)
    {
        // TODO: load logic
    }
}

, Dictionary<int, string>

public static class DictionaryExtensions
{
    public static void Save(this Dictionary<int, string> dictionary, string fileName)
    {
        // TODO: save logic
    }

    public static void Load(this Dictionary<int, string> dictionary, string fileName)
    {
        // TODO: load logic
    }
}
0

. , . , :

  public static class DictionaryExtensions
  {
        public static void Save(this Dictionary<int,string> yourDict, ...) {...}
        public static void Load(this Dictionary<int,string> yourdict, ...) {...}
  }

:

Dictionary<int,string> dict = ....;
dict.Save(...);
0

, IDictionary<TKey, TValue>, IXmlSerializable ( , , ). , - , - IDictionary<TKey, TValue>, Dictionary<TKey, TValue>.

: # , KeyValuePairs - , Dictionary. . , .

0

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


All Articles