【发布时间】:2011-09-01 13:29:23
【问题描述】:
我想创建一个自定义属性以应用于类中的任何方法,然后从该类外部访问已使用属性“标记”的类中的方法,以调用标记方法为如果是委托人。
例如
public delegate string MethodCall( string args);
和
public class MethodAttribute : System.Attribute
{
public MethodCall callback;
...
}
和
class TypeWithCustomAttributesApplied {
[Method]
public string DelegateMethod(string args) {
...
}
}
然后
void callMethods(string args) {
TypeWithCustomAttributesApplied myObj = new TypeWithCustomAttributesApplied();
DelegateMethod method = MyCustomerHelper.GetMarkedMethod(myObj)
method(args);
}
或许
void callMethods(string args) {
TypeWithCustomAttributesApplied myObj = new TypeWithCustomAttributesApplied();
MethodAttribute methodAtrib = MyCustomerHelper.GetMarkedMethod(myObj)
methodAtrib.callback(args);
}
我最终想要实现的是一个自定义属性,我可以使用它来“标记”任意类中的 Ajax 入口点,然后使用 Helper Class,将“Ajax Enabled”控件传递给识别哪个方法的助手在控件中调用,并将来自客户端的 ajax 数据交给它。无论如何,我对代表不是很好,但我通常了解如何应用自定义属性,但不确定如何“捕获”我正在“标记”的方法
我可能可以通过其他方式管理我的任务,但我正在尝试属性,所以我想先让这个方法起作用。
我的最终解决方案:
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() > 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));
}
}
}
【问题讨论】:
标签: c# custom-attributes