lundi 15 juillet 2019

Instantiate a reflected delegate type

I have a type variable

var validateFuncType = typeof(Func<,>).MakeGenericType(someVariableType, typeof(bool));

Now I check if someVariableType follows a convention,

var validateOfType = someVariableType
    .GetMethods(BindingFlags.Instance | BindingFlags.Public)
    .SingleOrDefault(mi =>
        {
            if (mi.Name != "Validate" || mi.ReturnType != typeof(bool))
            {
                return false;
            }

            var parameters = mi.GetParameters();
            return parameters.Length == 0;
        });

then depending on the check

if (validateOfType == null)
{
    validateFunc = // some noop func that returns true.
    // e.g.  _ => true;
}
else
{
    validateFunc = // a delegate that calls the conventional validate
    // e.g.  t => t.Validate();
}

instantiate an instance of the delegate type.

Can you help me do that, how can I instantiate validateFuncType?





Aucun commentaire:

Enregistrer un commentaire