Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 枚举的IRouteConstraint_Asp.net Mvc_Asp.net Mvc 2_Asp.net Mvc Routing_Url Routing - Fatal编程技术网

Asp.net mvc 枚举的IRouteConstraint

Asp.net mvc 枚举的IRouteConstraint,asp.net-mvc,asp.net-mvc-2,asp.net-mvc-routing,url-routing,Asp.net Mvc,Asp.net Mvc 2,Asp.net Mvc Routing,Url Routing,我想创建一个IRouteConstraint,根据枚举的可能值过滤一个值。 我试着自己用谷歌搜索它,但没有结果 有什么想法吗?见 基本上,你需要 private Type enumType; public EnumConstraint(Type enumType) { this.enumType = enumType; } public bool Match(HttpContextBase httpContext, Route route, s

我想创建一个IRouteConstraint,根据枚举的可能值过滤一个值。 我试着自己用谷歌搜索它,但没有结果

有什么想法吗?

基本上,你需要

  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());
  }

这就是我想到的:

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());
  }
}
我认为哈希集在每个匹配项上的性能都比Enum.GetNames好得多。此外,使用泛型使您在使用约束时看起来更流畅


不幸的是,其中T:Enum是编译器不允许的。

在我的博客上也是如此-Enum.IsDefined是区分大小写的,因此如果路由约束在不考虑大小写的情况下都有效,则应避免使用。不幸的是,如果编译器不允许T:Enum,则这是正确的,但您仍可以尝试在运行时强制执行它。如果T不是Enum:ArgumentException:Type,则构造函数Enum.GetNamesTypeSoft会引发异常。C 7.3添加了使用T:Enum的选项。然而,它并不像人们所期望的那样工作,参见