5
A
回答
4
見this
從本質上講,你需要
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());
}
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());
}
}
我認爲一個HashSet將執行不是在每個Enum.GetNames好得多比賽。此外,使用泛型讓您在使用約束時看起來更流暢。
不幸的是,編譯器不允許使用T:Enum。
相關問題
- 1. 通用枚舉約束
- 2. XmlSchemaException:枚舉約束失敗
- 3. Java通用綁定(約束)枚舉
- 4. 用於F#枚舉類型約束的用例?
- 5. JAX-RS球衣:用於枚舉異常映射約束FormParam
- 6. ServiceStack Ormlite多列約束失敗,其中約束包括枚舉
- 7. 枚舉具有蘊含約束條件的整數的m元組
- 8. 有條件地枚舉枚舉
- 9. 約束條件不適用於Ipad xamarin.forms
- 10. 約枚舉問題
- 11. 使用MySql從varchar到枚舉字段的外鍵約束
- 12. 約束在ADA中使用枚舉的錯誤警告
- 13. 用約束/條件迴歸
- 14. SQLServer2000約束條件
- 15. UITableViewCell約束條件
- 16. 前提條件可枚舉
- 17. C++枚舉和OR條件
- 18. CActiveDataProvider與條件值枚舉
- 19. Rails - 使用枚舉的Activerecord條件
- 20. POSTGRESQL的約束條件
- 21. 或QueryOver的約束條件
- 22. Mysql的約束與條件
- 23. 列的SQL約束條件
- 24. wCompact hRegular的約束條件
- 25. 檢查約束的條件
- 26. 用於枚舉源文件的插件
- 27. 條件MYSQL的唯一約束條件
- 28. 對於DayOfWeek的每條語句枚舉
- 29. 用於枚舉類
- 30. 約束條件適用於iOS 8,但不適用於iOS 7
在我的博客上 - http://mikemilleresq.wordpress.com/2010/03/12/starting-small-mvc-constraints/ – 2011-06-07 09:43:06
請參閱我的最終結果 – Jaap 2011-06-07 10:32:39
'Enum.IsDefined()'區分大小寫,所以應該避免,如果你的路由約束應該工作,無論大小寫。 – Chris 2014-04-04 11:23:23