4

我们正在升级我们糟糕的 cms 系统,新的程序集已从 int 更改为 int64。我现在尝试构建时遇到了问题。我试过铸造,但似乎没有帮助。这是导致问题的代码摘录。

IDictionary<int, string> aliases 
    = new UrlAliasApi().GetUrlAliasesByType(
        Company.DataLayer.Enumeration.UrlAliasType.Recipe);
foreach (ContentBase recipe in mergedResultset)
{
   // if alias exists, overwrite quicklink!
   string alias;
   if (aliases.TryGetValue(recipe.Id, out alias))
   {
      recipe.QuickLink = alias;
   }
}

错误是

错误 323 'System.Collections.Generic.IDictionary.TryGetValue(int, out string)' 的最佳重载方法匹配有一些无效参数

它指的是recipe.Id哪个是一个Int64值。

有什么想法可以解决这个问题吗?

4

5 回答 5

2

由于 C# 是强类型的,所以不能这样转换。在传入之前,您需要将 Int64 转换为 Int32:

aliases.TryGetValue((int)recipe.Id, out alias)

或者,您可以更改字典的定义:

IDictionary<Int64, string> aliases 
    = new UrlAliasApi().GetUrlAliasesByType(Company.DataLayer.Enumeration.UrlAliasType.Recipe)
                       .ToDictionary(kvp => (Int64)key.Key, kvp => kvp.Value);
于 2010-10-29T19:53:41.970 回答
1

The problem here is that you are trying to use an Int64 value in a place which takes an int/Int32 type. There is no implicit conversion here and hence the compiler errors.

The best way to fix this is to convert the aliases dictionary to use an Int64 type as well. It's always safe to convert an int to Int64 so there is no information loss in this conversion.

Ideally you'd convert GetUrlAliasesByType to return an IDictionary<Int64,string>. The rest of the system is now using Int64 so this conversion makes sense. Otherwise you can do the following

string alias; 
try { 
  if (aliases.TryGetValue(checked((int)recipe.Id), out alias)) 
  { 
    recipe.QuickLink = alias; 
  } 
} catch (OverflowException) { 
  // id not valid
}

The checked operation here is necessary because it prevents a silent overflow from producing a false match with TryGetValue

于 2010-10-29T19:55:36.353 回答
1

Note that while you can cast Int64 to Int32 (or int), you could lose some data if the values that you are casting are larger than can be represented in an Int32. In your case it might not matter, but I thought I should mention it.

于 2010-10-29T19:57:30.327 回答
1

您需要将Int64转换为int,如下所示:

aliases.TryGetValue((int)recipe.Id, out alias)
于 2010-10-29T19:53:51.280 回答
0

Why can't you just use Dictionary<Int64, string> instead of Dictionary<int, string>?

于 2010-10-29T19:54:58.297 回答