Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to identify and call a method tagged with an attribute
    primarykey
    data
    text
    <p>I'd like to create a custom attribute to apply to any method within a class, and then, from outside that class, access the method inside the class that has been 'tagged' with the attribute to call the tagged method as if it were a delegate.</p> <p>e.g.</p> <pre><code>public delegate string MethodCall( string args); </code></pre> <p>and</p> <pre><code>public class MethodAttribute : System.Attribute { public MethodCall callback; ... } </code></pre> <p>and</p> <pre><code>class TypeWithCustomAttributesApplied { [Method] public string DelegateMethod(string args) { ... } } </code></pre> <p>and then</p> <pre><code>void callMethods(string args) { TypeWithCustomAttributesApplied myObj = new TypeWithCustomAttributesApplied(); DelegateMethod method = MyCustomerHelper.GetMarkedMethod(myObj) method(args); } </code></pre> <p>or perhaps</p> <pre><code>void callMethods(string args) { TypeWithCustomAttributesApplied myObj = new TypeWithCustomAttributesApplied(); MethodAttribute methodAtrib = MyCustomerHelper.GetMarkedMethod(myObj) methodAtrib.callback(args); } </code></pre> <p>What I'm ultimately trying to achieve is a Custom Attribute that I can use to 'Mark' Ajax Entry points in arbitary classes, then with a Helper Class, pass the 'Ajax Enabled' control to the helper which identifies which method in the control to call, and hands it the ajax data from the client. I'm not so great with delegates anyway, but I generally understand how to apply custom attributes, but not sure how to 'capture' the method I'm 'tagging'</p> <p>I could probably manage my task some other way, but I'm trying my hand at attributes, so I'd like to get this method working first. </p> <hr> <p>My Final Solution :</p> <pre><code>public void CheckAjax(object anObject, string args) { MethodInfo[] methods = anObject.GetType().GetMethods(); foreach (MethodInfo method in methods) { object[] attributes = method.GetCustomAttributes(true); bool containsAttribute = (from attribute in attributes where attribute is AjaxableAttribute select attribute).Count() &gt; 0; if (containsAttribute) { string result_method = (string)method.Invoke(anObject, new object[] { args }); Log.Write(string.Format("The Result from the method call was {0} ", result_method)); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload