强制转换为基础词典 [英] Cast Derived to Base dictionary
本文介绍了强制转换为基础词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2本字典.如何将DerivedClass字典分配给DerivedClass字典?
I have 2 dictionaries. How I can assign DerivedClass dictionary to DerivedClass dictionary ?
下面的代码不担心吗?
如何更改它?
public class BaseClass
{
public void DoWork() { }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
class Program
{
static void Main(string[] args)
{
var derivedclass = new Dictionary<string, DerivedClass>();
var baseClass = new Dictionary<string, BaseClass>();
Dictionary<string, BaseClass> AAA = derivedclass;
Console.ReadKey();
}
}
推荐答案
您不能直接转换字典,但是可以创建一个新字典,类似这样的方法会起作用:
You can't cast the dictionary directly, but you can create a new dictionary, something like this will work:
Dictionary<string, BaseClass> AAA =
derivedclass.ToDictionary(
k => k.Key,
v => (BaseClass)v.Value);
这篇关于强制转换为基础词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文