用于枚举的IRouteConstraint

Jaa*_*aap 5 asp.net-mvc url-routing asp.net-mvc-routing asp.net-mvc-2

我想创建一个IRouteConstraint,它根据枚举的可能值过滤值.我试图为自己谷歌,但这并没有导致任何结果.

有任何想法吗?

Jaa*_*aap 9

这就是我想出的:

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.

  • *不幸的是,编译器不允许 T : Enum* 这是真的,但您仍然可以尝试在运行时强制执行它。http://stackoverflow.com/a/2936591/242520 (2认同)
  • 如果T不是枚举,则构造函数Enum.GetNames(typeof(T))抛出异常:ArgumentException:提供的类型必须是枚举. (2认同)

Ant*_*lev 5

看到这个

基本上,你需要

  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)