如果我有
public class Stats : Dictionary<string, double>
{
}
public class Info : Dictionary<string, Stats>
{
}
和
var data = new Dictionary<string, Dictionary<string, double>> {
{ "1", new Dictionary<string, double> { { "a", 11 } } },
{ "2", new Dictionary<string, double> { { "aa", 111 } } },
};
我为什么不能做:
var test = (Info)data;
以及我需要使用什么运算符或代码才能实例化我的
[从Dictionary< string,Dictionary< string,double>>继承的类]
从一个
字典< string,字典< string,double>> ;?
解决方法:
在这里,您的方法中确实存在两个不同的错误:
>字典< string,Stats>与Dictionary< string,Dictionary< string,double>不同.将Info视为继承Dictionary< string,Dictionary< string,double>>是错误的.它继承了完全不同的Dictionary< string,Stats>.
>即使您获得了正确的基本类型,也不能仅仅将基本类型的任何随机实例转换为派生类型.有关讨论此问题的众多现有Stack Overflow Q& A主题之一,请参见Convert/Cast base type to Derived type.
没有良好的Minimal, Complete, and Verifiable code example,就无法确定您的代码是如何工作的,或者要使它完成您想要的工作将需要什么.但是在您的特定示例中,您可能可以声明一个显式转换,该转换将在使用强制转换运算符时调用.
例如:
public class Info : Dictionary<string, Stats>
{
public static explicit operator Info(Dictionary<string, Dictionary<string, double>> source)
{
Info result = new Info();
foreach (var kvp in source)
{
result.Add(kvp.Key, Stats.FromDictionary(kvp.Value));
}
return result;
}
}
哪里:
public class Stats : Dictionary<string, double>
{
public static Stats FromDictionary(Dictionary<string, double> source)
{
Stats result = new Stats();
foreach (var kvp in source)
{
result.Add(kvp.Key, kvp.Value);
}
return result;
}
}
理想情况下,我们希望能够在Info中执行类似的操作:
public class Stats : Dictionary<string, double>
{
public static explicit operator Stats(Dictionary<string, double> source)
{
Stats result = new Stats();
foreach (var kvp in source)
{
result.Add(kvp.Key, kvp.Value);
}
return result;
}
}
但这是编译器错误:
Stats.explicit operator Stats(System.Collections.Generic.Dictionary)’: user-defined conversions to or from a base class are not allowed
此处更彻底地解决了这个问题:User-defined conversion operator from base class.简短的版本是,如果编译器允许这样做,那么如果您尝试从基本引用转换为派生引用,则意图是不明确的.在这种情况下,该语言会迫使您保持露骨.
然后,您要使用的语句将起作用:
var test = (Info)data;
话虽如此,您在评论中写道:
the class is just to clean up code and use my class name instead of
Dictionary<string, Dictionary<string, double>>
everywhere
如果是这样,那么您可能只想使用类型名称别名,而不是继承.例如:
using Stats = System.Collections.Generic.Dictionary<string, double>;
using Info = System.Collections.Generic
.Dictionary<string, System.Collections.Generic.Dictionary<string, double>>;
然后,您可以将名称Stats和Info与Dictionary< string,double>互换使用.和Dictionary< string,Dictionary< string,double>分别.
标签:generics,type-conversion,c 来源: https://codeday.me/bug/20191026/1939407.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。