隐式转换类型问题

时间:2011-08-18 13:30:04

标签: c# asp.net-mvc generics

我有以下课程:

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

我做错了什么,如何解决问题?

1 个答案:

答案 0 :(得分:3)

问题是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;
}