How to use a MethodInfo as a Delegate (EventHandler)

by JasonRShaver 9. December 2008 16:46

So, in doing some CSLA stuff, I wrote code something like the following:

MethodInfo ValidateMethod = type.GetMethod("ValidateType");
if (ValidateMethod != null)
{
	ValidationRules.AddRule(ValidateMethod, new RuleArgs(String.Empty));
}

and got the follow error: "Error 13 The best overloaded method match for 'CQSDKExtension.Csla.Validation.ValidationRules.AddRule(CQSDKExtension.Csla.Validation.RuleHandler, string)' has some invalid arguments"

Then I figured out that I could do the following:

if (ValidateMethod != null)
{
	ValidationRules.AddRule(Delegate.CreateDelegate(type, ValidateMethod), new RuleArgs(String.Empty));
}

but got this error: "Error 13 The best overloaded method match for 'CQSDKExtension.Csla.Validation.ValidationRules.AddRule(CQSDKExtension.Csla.Validation.RuleHandler, string)' has some invalid arguments"

So I did this:

MethodInfo ValidateMethod = type.GetMethod("ValidateType");
if (ValidateMethod != null)
{
	ValidationRules.AddRule((RuleHandler)Delegate.CreateDelegate(type, ValidateMethod), new RuleArgs(String.Empty));
}
And life was good.

Tags:

Blog

About the author

I am a software developer working for Microsoft in Redmond, WA.  In addition, my wife and I own TTXOnline, what is likely the 3rd largest table tennis store in the US.

Month List

Page List