我在C#中有一个方法
private IEnumerable<KeyValuePair<string, IEnumerable<KeyValuePair<string, SimpleRule>>>> GetPSPFlags(long Id, string promo, int vs)
{
const string qry = "select context, flag, name, rule " +
"from flags " +
"where id = :pId " +
"and code = :pc " +
"and vs = :v "
var p = new OracleParameter[3];
p[0] = new OracleParameter(":pId", Id);
p[1] = new OracleParameter(":pc", promo);
p[2] = new OracleParameter(":v", vs);
string error;
var results = Select(qry, p, out error);
if (!string.IsNullOrEmpty(error)) throw new ApplicationException(error);
return results.Rows.Cast<DataRow>().ToDictionary(row => ToString(row["flag"]), row => SimpleRuleParser.GetRule(ToString(row["rule"])));
}
返回类型时出现错误。如何返回上下文,标志,名称和规则的集合?
答案 0 :(得分:0)
我假设rule_vpath
返回一个SimpleRuleParser.GetRule
。如果您想以Dictionary<string, SimpleRule>
的枚举形式返回规则,则将值强制转换为该类型
KeyValuePairs
您收到的错误是因为您无法投射
return results.Rows.Cast<DataRow>().ToDictionary(
row => ToString(row["flag"]),
row => (IEnumerable<KeyValuePair<string, SimpleRule>>)SimpleRuleParser.GetRule(
ToString(row["rule"]))
);
到
IEnumerable<KeyValuePair<string, Dictionary<string, SimpleRule>>>
我为解析值引入的强制转换会导致您获得
IEnumerable<KeyValuePair<string, IEnumerable<KeyValuePair<string, SimpleRule>>>>
实现所需的方法返回类型
Dictionary<string, IEnumerable<KeyValuePair<string, SimpleRule>>>
您的问题是关于泛型类型的协方差和协变。另请参阅我对这个问题的answer:C# 3.0 implicit cast error with class and interfaces with generic type
注意:IEnumerable<KeyValuePair<string, IEnumerable<KeyValuePair<string, SimpleRule>>>>
的优点是它允许通过键非常快速地访问值,而必须始终枚举Dictionary<,>
才能找到特定的条目。因此,实际上可能最好通过原始类型IEnumerable<>
返回结果。