使用带out参数的dynamic调用方法 [英] Calling a method using dynamic with an out parameter

查看:139
本文介绍了使用带out参数的dynamic调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  dynamic dict = GetDictThroughMagic(); 
动态d;
bole hasValue = dict.TryGetValue( name,out d);
bole hasValue = dict.TryGetValue( name,d);

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



但是我更愿意编写更简洁的TryGetValue方法。



已更新,包括实际异常:

 未处理的异常:Microsoft.CSharp.RuntimeBinder .RuntimeBinderException:
最佳重载方法匹配'System.Collections.Generic.Dictionary< string,K>
.TryGetValue(string,out K)'在CallSite.Target(Closure,CallSite,Object,String,Object&)
中有一些无效的参数
。 pre>

解决方案

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



但是您可以通过切换哪个参数为 out 以及哪个为返回值来解决此问题,尽管使用该参数将不如普通的 TryGetValue()

 静态类DictionaryHelper 
{
public static TValue TryGetValue< TKey,TValue>(
字典< TKey,TValue> dict,TKey值,出布尔值)
{
TValue结果;找到
= dict.TryGetValue(值,超出结果);
的返回结果;
}
}

您可以这样称呼它:

 动态字典= GetDictThroughMagic(); 
bole hasValue;
动态d = DictionaryHelper.TryGetValue(dict, name,hasValue);


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

解决方案

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

这篇关于使用带out参数的dynamic调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆