mardi 5 novembre 2019

How to Invoke a private field generically?

I have a generic method to get private Field using reflection:

 static internal TReturn GetPrivateField<TInstance, TReturn>(TInstance instance, string fieldName)
    {
        Type type = instance.GetType();
        var obj = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
        return (TReturn)obj.GetValue(instance);
    }

But I want to write a similar function that can get this private field using Invoke. My pupose is to remove this kind of code:

string text = "";
frm.cbo.Invoke((MethodInvoker)delegate() { text = frm.cbo.Text; });

and replace it by a call to my function.

I find this question but they speak about calling a method and not a field.

I didn't find a solution to make my function generic and access private field of my instance. How to do such a function?

I gave a sample of the kind of code i want to replace in case there is an other way to solve this kind of problems.





Aucun commentaire:

Enregistrer un commentaire