dimanche 23 octobre 2022

Call a method on any field of a specific type c#

I know that is easy with reflection to find a property of a specific name and call a method on it

            var fields = this.GetType().GetFields(BindingFlags.NonPublic |
                         BindingFlags.Instance).Where(x=>x.FieldType == typeof(IMyType));

            foreach (var field in fields)
            {
                var myMethod = typeof(ITenantService).GetMethod("MyMethod");
                var test = myMethod ?.Invoke(field, new object[]
                {
                    myParameter
                });
            }

This doesnt work because field is FieldInfo. GetFieldValue is a string which is of no use

How can I do this please?

What I am aiming for in the end is for something that given a type I find all of the fields that have a field of a specific type, and call my method on that field

Cheers

Paul





Aucun commentaire:

Enregistrer un commentaire