Calling a method using dynamic with an out parameter

为君一笑 提交于 2019-12-13 13:42:32

问题


I have a Dictionary<string,K> where K is a type that is loaded through reflection, I can't name K.

Unfortunately, I can't figure out how I'm supposed to use the TryGetValue method. I tried a couple of different things and they all lead to exceptions. What am I suppose to do?

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

I can write the more verbose if(dict.Contains("name")) d=dict["name"]

But I'd prefer if I could write the more concise TryGetValue approach.

Updated to include actual exception:

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& )

回答1:


You can't do that, because in .Net, variables used as ref and out parameters must match the type exactly. And a dynamic variable is actually an object variable at runtime.

But you could work around that by switching which parameter is out and which is the return value, although working with that would be less nice than normal 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;
    }
}

You could then call it like this:

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



回答2:


Why are you using a dynamic? Is this coming via an interop? I would suggest using a common abstraction that can be used here. Reflection does not mean dynamic, and this keyword is being thrown around in a static language in places that it is not needed. It was designed for interops...

More specific to your question: Here is what seems like a good answer. I do not believe that the cast can work here because it cannot cast up to type K.




回答3:


I recently came across the similar error but came to a solution making all access to the dictionary dynamic.

Try

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;
} 

Hope this works out for you!



来源:https://stackoverflow.com/questions/10021265/calling-a-method-using-dynamic-with-an-out-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!