3

我有一个Dictionary<string,K>where K 是通过反射加载的类型,我不能命名 K。

不幸的是,我无法弄清楚我应该如何使用该TryGetValue方法。我尝试了几种不同的方法,它们都导致异常。我该怎么办?

dynamic dict = GetDictThroughMagic();
dynamic d;
bool hasValue = dict.TryGetValue("name",out d);
bool hasValue = dict.TryGetValue("name",d);

我可以写得更详细if(dict.Contains("name")) d=dict["name"]

但如果我可以编写更简洁的 TryGetValue 方法,我会更喜欢。

更新以包括实际异常:

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The
best overloaded method match for 'System.Collections.Generic.Dictionary<string,K>
.TryGetValue(string, out K)' has some invalid arguments
   at CallSite.Target(Closure , CallSite , Object , String , Object& )
4

3 回答 3

3

您不能这样做,因为在.Net 中,用作refout参数的变量必须与类型完全匹配。dynamic变量实际上是运行时的object变量。

但是您可以通过切换哪个参数是哪个参数是out返回值来解决这个问题,尽管使用它会比正常情况下好TryGetValue()

static class DictionaryHelper
{
    public static TValue TryGetValue<TKey, TValue>(
        Dictionary<TKey, TValue> dict, TKey value, out bool found)
    {
        TValue result;
        found = dict.TryGetValue(value, out result);
        return result;
    }
}

然后你可以这样称呼它:

dynamic dict = GetDictThroughMagic();
bool hasValue;
dynamic d = DictionaryHelper.TryGetValue(dict, "name", out hasValue);
于 2012-04-05T01:14:28.920 回答
1

你为什么用一个dynamic?这是通过互操作来的吗?我建议使用可以在这里使用的通用抽象。反射并不意味着动态,并且这个关键字在静态语言中被扔在不需要它的地方。它是为互操作而设计的...

更具体到您的问题:这似乎是一个很好的答案。我不相信演员表可以在这里工作,因为它不能转换为 K 型。

于 2012-04-05T00:57:22.930 回答
0

我最近遇到了类似的错误,但找到了一个解决方案,使所有对字典的访问都是动态的。

尝试

dynamic dict = GetDictThroughMagic();
dynamic value = "wacka wacka"; // I renamed from 'd' and gave it a value
dynamic key = "name";

if (dict.ContainsKey(key))
{
    dict[key] = value;
} 

希望这对你有用!

于 2013-12-11T14:37:43.120 回答