即使已定义显式强制转换运算符,也会出现InvalidCastException

时间:2014-06-04 09:37:11

标签: c#

很奇怪。我的显式强制转换操作符不起作用。

我有一个像这样定义的强制转换运算符:

public class OAuthClient
{
  public string LoginUrl { get; set; }
  public string ImagePath { get; set; }
  public string ImageTitle { get; set; }
  public string ImageAlt { get; set; }

  public static OAuthClient FromFrameworkOAuthClient(
              BaseServices.OAuth.IOAuthClient client)
  {
    return new OAuthClient
    {
      LoginUrl = client.LoginUrl,
      ImagePath = client.ImagePath,
      ImageTitle = client.ImageTitle,
      ImageAlt = client.ImageAlt
    };
   }

   public static OAuthClient FromGoogleClient(GoogleClient client)
   {
     return FromFrameworkOAuthClient(client);
   }

   public static OAuthClient FromFacebookClient(FacebookClient client)
   {
     return FromFrameworkOAuthClient(client);
   }

   public static explicit operator OAuthClient(BaseServices.OAuth.FacebookClient client)
   {
     return FromFrameworkOAuthClient(client);
   }

   public static explicit operator OAuthClient(BaseServices.OAuth.GoogleClient client)
   {
     return FromFrameworkOAuthClient(client);
   }
  }
}

然后在Controller方法中,我这样做:

protected virtual IEnumerable<ViewModels.OAuthClient> GetViewModelOAuthClients(
                   IEnumerable<IOAuthClient> oAuthClients)
{
  oAuthClients.ForEach(client => { client.GetLoginUrl(); });

  return oAuthClients.Select(c => (ViewModels.OAuthClient)c);
}

奇怪的是,我得到一个InvalidCastException说,无法将“BaseServices.OAuth.FacebookClient”类型的对象转换为“Web.Presentation.ViewModels.OAuthClient”。

我无法弄清楚发生了什么。这很奇怪。我肯定错过了一些非常小的东西。帮助赞赏。

1 个答案:

答案 0 :(得分:2)

我从BaseServices.OAuthClientViewModels.OAuthClient创建了另一个特定的显式广播,如下所示:

public static explicit operator OAuthClient(BaseServices.OAuth.OAuthClient client)
{
  return FromFrameworkOAuthClient(client);
}

然后将IEnumerable<IOAuthClient>中的每个项目首先投放到BaseServices.OAuthClient,然后投放到ViewModels.OAuthClient

protected virtual IEnumerable<ViewModels.OAuthClient> GetViewModelOAuthClients(
                 IEnumerable<IOAuthClient> oAuthClients)
{
  oAuthClients.ForEach(client => { client.GetLoginUrl(); });

  return oAuthClients.Select(c => (ViewModels.OAuthClient)(OAuthClient)c);
}

那很有效。