[英]Adding values to a dynamic type causes a RuntimeBinderException
I am working on building a UITypeEditor
(launched from the property grid) to edit a Dictionary<T,T>
where T
could be any scalar type ( int
, long
, double
, string
, DateTime
, etc.). 我正在构建一个
UITypeEditor
(从属性网格启动)来编辑Dictionary<T,T>
,其中T
可以是任何标量类型( int
, long
, double
, string
, DateTime
等)。 The dictionary to be edited is passed into the control as an object
named innerobject
. 要编辑的字典作为名为
innerobject
的object
传递到控件中。 I get the type and key-value types as following: 我得到的类型和键值类型如下:
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;
Later when I try to add values to it, I do the following (s is one line in the textbox): 稍后,当我尝试向其中添加值时,我将执行以下操作(s是文本框中的一行):
string[] str = s.Split(new char[] { ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (str.Length == 2)
{
object a = keyconverter.ConvertFromString(str[0]);
object b = valueconverter.ConvertFromString(str[1]);
dyndic[a] = b;
}
A Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
is thrown at this point. 此时将引发
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.
You need a
and b
to be dynamic also: 您还需要
a
和b
来保持动态:
dynamic a = keyconverter.ConvertFromString(str[0]);
dynamic b = valueconverter.ConvertFromString(str[1]);
dyndic[a] = b;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.