samedi 1 octobre 2016

Cloning a Class Definition (PCL)

The Question: Is this possible to clone a class definition using reflection? I am not talking about shallow cloning nor deep cloning. I am talking about definition cloning. I want to have a class with a static variable not shared between all instances, but just the definition I created. And I (or the library) need to be able to create an instance from this class later on.

The Problem: You see, I need this because of the following scenario,

There is this library that expects me to provides it with a type having a certain static method. However in my case this static method needs to compare two value one from a non static field of another type. This makes it impossible to pass the instance that has the information to the class because it is not yet initialized. Check out the following example of the situation:

class MasterClass 
{
    public int SomeInfo {get; set;} = 10;
    public void PeresentClass()
    {
        SOMELIBRARY.RegisterType(typeof(StaticClass));
    }
}
class StaticClass
{
    public static bool CanCreate(int someVar)
    {
        // I need to compare someVar with the SomeInfo property of MasterClass instance that presented this type to the SOMELIBRARY.
    }
    public StaticClass()
    {
        // Something irrelevant
    }
}

In the above example I have no control over the SOMELIBRARY and the way they decided to write the code. But it seems that they some how want to call the CanCreate method first and then create an instance of class if it meets the requirements.

However, for CanCreate to works correctly I need to have access to the instance of the class presented the StaticClass to the SOMELIBRARY in first place. And I cant make MasterClass static because there are more than one instance of this class active at every time.

Only way I could think of was to redefine a new StaticClass with a static field pointing to the MasterClass that defined it (or cloned the definition). However my knowledge of reflection failed me to do so yet. So here I am asking it this is even possible? And I really would like to be able to do it under PCL profiles.

Real World: Just for more information, I am actually talking about XAMARIN.iOS and NSUrlProtocol class. Specially CanInitWithRequest and StartLoading methods.





Aucun commentaire:

Enregistrer un commentaire