C # Use ILGenerator to dynamically generate a function,
There is always a lot of configuration files to read on the game server, and the reading of these configuration files: * otherwise, it will be a bunch of strings or numbers, you cannot see the error (you need to check it again) * otherwise, it will be forced. You need to Parse each type.
I personally like the latter because the LoadConfig code of the former is simple, but the code is not simple when writing logic.
1 class Config1 : public IConfig { 2 public void Fill(EntryLine& line); 3 int32_t param1; 4 string param2; 5 std::vector<int32_t> param3; 6 }; 7 8 void Config1::Fill(EntryLine& line) { 9 this->param1 = line.ReadInt32();10 this->param2 = line.ReadString();11 this->param3 = line.ReadVectorInt32();12 }
The approximate filling function is written above,ReadInt32
This kind of function is fictitious and needs to be implemented by yourself (HUM)
Then this code is very annoying to write, and I don't really want to write it. This is the reason for this article.
C # There is XML deserialization in it. I define a class:
1 class Config1 {2 int32 param1;3 string param2;4 int[] param3;5 }6 7 XmlSerializer serializer = new XmlSerializer(typeof(Config1));8 var obj = (Config1)serializer.Deserialize(stream);
This deserialization is very simple. I actually want this thing, but Xml deserialization uses Node, and I want to use attributes, the other is the attribute value. I have some personalized things in it.
Thanks to Microsoft for providing the function of debugging the. NET Framework, so that I can debug the. NET source code and see how Microsoft implements it.
After some research, he found that he wasXmlSerializer
When constructingConfig1
Analyzed, and then generated some metadata, andRead/Write
Method, Deserialize just calledRead
Method.
Now that you know how he implements it, you must study it for a while, and then you can discover it.
Basically, you have to extract onePrototype
And thenPrototype
Procedural.
PS: the performance has not been tested yet, so it should not be too bad. The worst is that the server starts slowly for several seconds.
XmlSerializationReaderILGen. cs