Jaa*_*aap 5 asp.net-mvc url-routing asp.net-mvc-routing asp.net-mvc-2
我想创建一个IRouteConstraint,它根据枚举的可能值过滤值.我试图为自己谷歌,但这并没有导致任何结果.
有任何想法吗?
这就是我想出的:
public class EnumRouteConstraint<T> : IRouteConstraint
where T : struct
{
private readonly HashSet<string> enumNames;
public EnumRouteConstraint()
{
string[] names = Enum.GetNames(typeof(T));
enumNames = new HashSet<string>(from name in names select name.ToLowerInvariant());
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return enumNames.Contains(values[parameterName].ToString().ToLowerInvariant());
}
}
Run Code Online (Sandbox Code Playgroud)
我认为HashSet在每场比赛中的表现要比Enum.GetNames好得多.使用泛型也使得它在使用约束时看起来更流畅.
不幸的是,编译器不允许使用T:Enum.
看到这个
基本上,你需要
private Type enumType;
public EnumConstraint(Type enumType)
{
this.enumType = enumType;
}
public bool Match(HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
// You can also try Enum.IsDefined, but docs say nothing as to
// is it case sensitive or not.
return Enum.GetNames(enumType).Any(s => s.ToLowerInvariant() == values[parameterName].ToString());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1364 次 |
| 最近记录: |