I've been struggling a bit with a tricky scenario. Let's get into it.
This question is similar to my issue. The difference is that I need to build the delegate only once, allowing the instance (target) to be many different values. In other words, I will not have any way to access an instance at the time the delegate is built.
If I can convert the instance MethodInfo
into an extension MethodInfo
, that would suit my needs.
The question is done here, but there's more context below:
What I'm working with is server software (Specifically DarkRift for Unity) where data is sent by reading and writing to a stream (DarkRiftReader
s and DarkRiftWriter
s). There is the option to implement IDarkRiftSerializable
and define methods Serialize(event with writer)
and Deserialize(event with reader)
. I'm writing a class that automatically generates those methods through reflection (Gets all fields of the derived class, uses them to build instructions on how to serialize and deserialize).
I have two methods that take in a type parameter and return a delegate to serialize or deserialize data of that type. These methods search both built in methods of the reader and writer types, along with extension methods.
Here's a snippet of the deserializer method for context:
// GetReader - expensive method, only run once to build the deserializer.
// Searches assemblies for suitable methods and passes them back to the deserializer.
// Methods = built in methods, Extensions = extension methods loaded
...
var method = Methods.FirstOrDefault(m => m.ReturnType == type);
if (method != null) return reader => method.Invoke(reader, null);
method = Extensions.FirstOrDefault(m => m.ReturnType == type);
if (method != null) return reader => method.Invoke(null, new object[] { reader });
...
Currently they use MethodInfo.Invoke
but I would much prefer they return a delegate created by the MethodInfo
s for optimization's sake.
I'm open to any discussion on this.
Aucun commentaire:
Enregistrer un commentaire