C# 向动态类型添加值会导致RuntimeBinderException
我正在构建一个C# 向动态类型添加值会导致RuntimeBinderException,c#,.net,dynamic,C#,.net,Dynamic,我正在构建一个UITypeEditor(从属性网格启动)来编辑字典,其中T可以是任何标量类型(int,long,double,string,DateTime,等等)。 要编辑的词典作为名为innerobject的对象传递到控件中。我得到的类型和键值类型如下: Type t = innerobject.GetType(); Type[] member_t = innerobject.GetType().GetGenericArguments(); if(member_t.Length !=2)
UITypeEditor
(从属性网格启动)来编辑字典,其中T
可以是任何标量类型(int
,long
,double
,string
,DateTime
,等等)。
要编辑的词典作为名为innerobject
的对象传递到控件中。我得到的类型和键值类型如下:
Type t = innerobject.GetType();
Type[] member_t = innerobject.GetType().GetGenericArguments();
if(member_t.Length !=2)
return null;
var keyconverter = TypeDescriptor.GetConverter(member_t[0]);
var valueconverter = TypeDescriptor.GetConverter(member_t[1]);
if (null == keyconverter || null == valueconverter)
return null;
var dic = Activator.CreateInstance(t);
dynamic dyndic = dic;
稍后,当我尝试向其添加值时,我会执行以下操作(文本框中只有一行):
此时将抛出一个Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Unknown Module.
Additional information: The best overloaded method match for 'System.Collections.Generic.Dictionary<double,double>.this[double]' has some invalid arguments. If there is a handler for this exception, the program may be safely continued.
未知模块中发生了类型为“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”的首次意外异常。
其他信息:“System.Collections.Generic.Dictionary.this[double]”的最佳重载方法匹配具有一些无效参数。如果存在此异常的处理程序,则程序可以安全地继续。
您还需要a
和b
动态:
dynamic a = keyconverter.ConvertFromString(str[0]);
dynamic b = valueconverter.ConvertFromString(str[1]);
dyndic[a] = b;
dynamic a = keyconverter.ConvertFromString(str[0]);
dynamic b = valueconverter.ConvertFromString(str[1]);
dyndic[a] = b;