隐式转换类型问题
本文关键字:问题 类型 转换 | 更新日期: 2023-09-27 18:05:53
我有以下类:
public class DictionaryBuilder<T> where T : IDictionary<string, object>, new()
{
private List<Tuple<string, object>> values_ = new List<Tuple<string, object>>();
public DictionaryBuilder<T> WithValue(string key, object obj)
{
values_.Add(Tuple.Create(key, obj));
return this;
}
public static implicit operator T(DictionaryBuilder<T> builder)
{
return builder.Build();
}
public T Build()
{
var dict = new T();
foreach (var value in values_)
{
dict.Add(value.Item1, value.Item2);
}
return dict;
}
}
public static class Admin
{
public static string IndexPath { get { return "Admin/Index"; } }
public static DictionaryBuilder<RouteValueDictionary> IndexRoute
{
get
{
return new DictionaryBuilder<RouteValueDictionary>()
.WithValue("controller", "Admin")
.WithValue("action", "Index");
}
}
}
它的用法是:
@Html.RouteLink("Admim",
Admin.IndexRoute
.WithValue("id",3),
new DictionaryBuilder<Dictionary<string,object>>()
.WithValue("class","AdminRouteLink")
这有点拗口,泛型对意图有一点阻碍。我想这样做:
public class RouteValues : DictionaryBuilder<RouteValueDictionary> { }
public class HtmlValues : DictionaryBuilder<Dictionary<string,object>> { }
public static class Admin
{
public static string IndexPath { get { return "Admin/Index"; } }
public static RouteValues IndexRoute
{
get
{
return new RouteValues()
.WithValue("controller", "Admin")
.WithValue("action", "Index");
}
}
}
@Html.RouteLink("Admim",
Admin.IndexRoute
.WithValue("id",3),
new HtmlValues()
.WithValue("class","AdminRouteLink")
不幸的是,我得到一个转换错误,恐怕我不完全理解:
Cannot implicitly convert type
'ControllerActionExporter
.DictionaryBuilder<System.Web.Routing.RouteValueDictionary>'
to
'ControllerActionExporter.RouteValues'.
An explicit conversion exists (are you missing a cast?)
return new RouteValues()
.WithValue("controller", "Admin")
.WithValue("action", "Index"); //error occurs on this line
我做错了什么,我如何纠正这个问题?
问题是WithValue
返回DictionaryBuilder<T>
,但IndexRoute
属性返回更具体的类型RouteValues
。尝试更改属性以返回DictionaryBuilder<T>
:
public static DictionaryBuilder<RouteValueDictionary> IndexRoute
{
get
{
return new RouteValues()
.WithValue("controller", "Admin")
.WithValue("action", "Index");
}
}
另一种方法是为DictionaryBuilder<T>
类创建一个泛型扩展方法,该方法返回与传入的类型相同的类型:
public static T WithValue(this T builder, string key, object obj)
{
builder.WithValue(key, obj);
return builder;
}