C# 获取Func的属性
我需要检查传入的C# 获取Func的属性,c#,reflection,func,C#,Reflection,Func,我需要检查传入的Func中的特定属性 到目前为止,我已经: var methodInfo = cachedMethod.GetMethodInfo(); var isCachable = methodInfo.CustomAttributes. Any(x => x.AttributeType == typeof(CachedAttribute)); 但是,我发现CustomAttributes属性为空 找到应用于传入func的属性的正确方法
Func
中的特定属性
到目前为止,我已经:
var methodInfo = cachedMethod.GetMethodInfo();
var isCachable = methodInfo.CustomAttributes.
Any(x => x.AttributeType == typeof(CachedAttribute));
但是,我发现CustomAttributes属性为空
找到应用于传入func的属性的正确方法是什么?在我的例子中,func是另一个类中的静态方法
更新
下面是一个小示例,展示了我如何尝试使用它:
HTML帮助程序:
public static IHtmlString CachedPartial<TModel>(this HtmlHelper helper,
string partialName,
TModel model,
Func<string, string> cachedMethod)
{
var methodInfo = cachedMethod.GetMethodInfo();
var isCachable = methodInfo.IsDefined(typeof (CachedAttribute));
if (!isCachable)
{
throw new Exception("...");
}
return new MvcHtmlString(cachedMethod("foo"));
}
@Html.CachedPartial("Foo",
Model,
HtmlHelperExtensions.GenrateSiteMapGraphHtml)
这是从Razor视图调用的:
public static IHtmlString CachedPartial<TModel>(this HtmlHelper helper,
string partialName,
TModel model,
Func<string, string> cachedMethod)
{
var methodInfo = cachedMethod.GetMethodInfo();
var isCachable = methodInfo.IsDefined(typeof (CachedAttribute));
if (!isCachable)
{
throw new Exception("...");
}
return new MvcHtmlString(cachedMethod("foo"));
}
@Html.CachedPartial("Foo",
Model,
HtmlHelperExtensions.GenrateSiteMapGraphHtml)
我可能不太明白你的问题是什么,但我建议两件事:
因此,请检查该类在您试图调用该静态方法的代码区域中是否可见如果您可以显示一个简短但完整的程序来演示该问题,这会有所帮助。顺便说一句,您确实需要使用
CustomAttributes
而不仅仅是IsDefined
?(这似乎不太可能是在仅反射的上下文中加载的…)我不知道IsDefined
,因此我可以用它替换CustomAttributes
部分。但是,在检查属性时,仍然返回false
。我将发布一个示例程序。您是否尝试过使用Delegate.Method
而不是GetMethodInfo
扩展方法?我不知道区别是什么,如果有的话……是的,我刚刚尝试过:cachedMethod.Method.IsDefined(typeof(CachedAttribute))代码>再说一遍,一个简短但完整的程序确实会有帮助-例如,你能在ASP.NET之外演示一下吗?使用控制台应用程序进行尝试会更容易。根据@jon skeet注释,我的答案中与“NULL”的抽象比较应替换为IsDefined。感谢您的回答。方法的可见性似乎很好,我可以毫无问题地执行它。我只需要检查一个现有的属性(在本例中,我知道它存在)。