c# - Reflection on enum extension method located in separate assembly -
this question has answer here:
- reflection identify extension methods 6 answers
code have:
public enum activitystatus { = 0, active = 1, inactive = 2 } public static class myclass { public static string test(this activitystatus _value) { return _value + "111"; } }
and typeof(activitystatus).getmethods()
doesn't contain test method. tried put in same assembly, still no success. wrong?
extension methods static methods, compiler translates call
yourenum.test();
to:
myclass.test(yourenum);
so in order test
method info via reflection, need inspect myclass
, activitystatus
parameter there.
var testmethodinfo = typeof(myclass).getmethod("test"); var firstparameter = testmethodinfo.getparameters()[0]; console.writeline (firstparameter.parametertype + " " + firstparameter.name);
prints:
activitystatus _value
if want all extension methods type in particular assembly, can use next code:
var extensionmethodsforactivitystatus = typeof(activitystatus) //type assembly search .assembly //pick assembly .gettypes() //get types there .selectmany(t => t.getmethods()) //get methods type .where(m => m.getparameters().any() && m.getparameters().first().parametertype == typeof(activitystatus)) //check if first parameter our enum .where(m => m.isdefined(typeof(extensionattribute), true)); //check if method extension method foreach(var extensionmethod in extensionmethodsforactivitystatus) console.writeline(extensionmethod.name); //prints test
Comments
Post a Comment