c#动态字典中的值
本文关键字:字典 动态 | 更新日期: 2023-09-27 18:09:13
这个问题可能有点渺茫,但请继续阅读:
我有一组正在运行的存储过程,它们的所有数据都存储在字典中。
例如getEventTypes存储在eventtyperresult字典中,getEventCats存储在eventCatResult字典中。
是否可以动态运行以下行:
Dictionary<string, eventTypeResult> resultsList = (Dictionary<string, eventTypeResult>)resultsObject;
可以像这样:
var resultType = eventTypeResult;
Dictionary<string, resultType > resultsList = (Dictionary<string, resultType >)resultsObject;
谢谢你的帮助。
尝试解释为什么它需要是动态的
目前我的代码是这样的:
if (resultType == "eventTypeResult")
{
Dictionary<string, eventTypeResult> resultsList = (Dictionary<string, eventTypeResult>)resultsObject;
}
else if (resultType == "eventDateResult")
{
Dictionary<string, eventDateResult> resultsList = (Dictionary<string, eventDateResult>)resultsObject;
}
else if
else if
else if
ect
ect
可以这样吗:
var resultType = eventTypeResult;
Dictionary<string, resultType > resultsList = (Dictionary<string, resultType >)resultsObject;
"动态"可能不是强类型语言中最好的方法…你试图创建的是一个任意的名称值集合,就像。net框架中的各种缓存类型一样。您需要依赖一个通用的类型,它可以容纳所有的结果类型。
如果您有像resultType
这样的类型,所有其他结果类型都继承它,则使用: Dictionary<string, resultType >
。你可以把任何你想要的值,只要它是resultType
的子类。如果你不这样做,那么使用Dictionary<string, object >
如果你需要在字典之间强制转换,你总是可以(对象的实际类型必须匹配):
var thing = new Dictionery<int> ()
var objectThing = thing.Cast<Dictionery<object>();
如果你想要动态的,可以:
Dictionary<string, resultType > dict;
dyamic value = dict["something"];
value.WhaterverYouWant() // if this method doesnt exist this will compile but crash at runtime...