将值添加到动态类型会导致RuntimeBinderException

时间:2014-12-18 19:06:37

标签: c# .net dynamic

我正在制作一个UITypeEditor(从属性网格中启动)来修改Dictionary<T,T>,其中T可以是任何标量类型(int,{{1 }},longdoublestring等。 要编辑的字典作为名为DateTime的{​​{1}}传递到控件中。我得到类型和键值类型如下:

object

稍后当我尝试向其添加值时,我会执行以下操作(s是文本框中的一行):

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;

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

1 个答案:

答案 0 :(得分:1)

您还需要ab动态:

dynamic a = keyconverter.ConvertFromString(str[0]);
dynamic b = valueconverter.ConvertFromString(str[1]);
dyndic[a] = b;