Home > Article > Backend Development > How to use ILGenerator in C# to dynamically generate instances of functions
This article mainly introduces the simple code of C# using ILGenerator to dynamically generate functions. Friends who need it can refer to it
There are always a lot of configuration files in the game server that need to be read, and these configuration files Reading: * Otherwise, it will be made into a weak type, which is just a bunch of strings or numbers, and the error cannot be seen (it needs to be checked again) * Otherwise, it will be made into a strong type, and each type needs to be parsed by itself
I personally prefer the latter, because the former LoadConfig code is simple, but the code is not simple when writing logic.
class Config1 : public IConfig { public void Fill(EntryLine& line); int32_t param1; string param2; std::vector<int32_t> param3; }; void Config1::Fill(EntryLine& line) { this->param1 = line.ReadInt32(); this->param2 = line.ReadString(); this->param3 = line.ReadVectorInt32(); }
The approximate filling function is as above As written, it’s just that functions like ReadInt32 are fictitious and you need to implement them yourself (hum)
Then this kind of code is very annoying to write, and I don’t really want to write it. This is the reason for this article.
There is XML deserialization in C#. I define a class:
class Config1 { int32 param1; string param2; int[] param3; } XmlSerializer serializer = new XmlSerializer(typeof(Config1)); var obj = (Config1)serializer.Deserialize(stream);
This deserialization is very simple. This is what I actually want. It’s just that Xml deserialization uses Node, and I want to use attributes. The other one is the value of the attribute. I have some personalized things in it.
Thanks to Microsoft for providing the function of debugging .NET Framework. Let me debug the .NET source code and see how Microsoft implements it.
After some research, I found that he actually analyzed Config1 when XmlSerializer was constructed, and then generated some metadata. And the Read/Write method, Deserialize just calls the Read method.
Now that you know how it is implemented, I believe you can figure it out after a while.
Basically you You have to build a prototype first, and then program the prototype.
PS: I haven’t tested the performance yet, so it shouldn’t be too bad. The worst thing is that the server starts a few seconds slower.
XmlSerializationReaderILGen.cs
Summary
The above is the detailed content of How to use ILGenerator in C# to dynamically generate instances of functions. For more information, please follow other related articles on the PHP Chinese website!