随着自定义属性和反射的大量学习曲线,我似乎仍在挣扎。任何人都可以帮我解决这个问题吗?通过CustomAttribute获取方法,然后调用
基本上我想调用一个基于它的属性的方法。
这是装饰方法的CustomAttribute(它将永远只能是一个方法): [ControllerName(NAME = “博客”)
public static string GetContent(string controllerName, string singleItemName = "")
{
string returnVal = null;
//Get the class type
Type thisType = typeof(ContentFacade);
//Get member info
System.Reflection.MemberInfo info = typeof(ContentFacade);
Loop through attributes
foreach (object attrib in info.GetCustomAttributes(true))
{
//if the attribute matches the param controller name
//then invoke
if (attrib == controllerName)
{
//Get the method by attribute not method name
//I dont want to get the method by MethodName
MethodInfo theMethod = thisType.GetMethod(controllerName);
//Return the value as it will be html for the end user
returnVal = (string)theMethod.Invoke(controllerName, null);
}
}
return returnVal;
}
同样,如果可能的话,我想通过属性获取方法。
真的很期待在这方面得到一些帮助。
///编辑 对不起,我在代码中添加了注释来说明问题。 基本上我想:
- 找controllerName属性==“博客”
- 通过属性获取方法和调用
我不想获得由法方法名称。
问候,
你有什么实际问题? –
我确实认为你的问题比“方法的名称是什么”更符合逻辑。想一想你想做什么,一切都会变得简单。你发布的代码似乎有逻辑问题。 – xanatos
@xanatos好诡秘的评论:)精心制作? –