【问题标题】:Adding values to a dynamic type causes a RuntimeBinderException向动态类型添加值会导致 RuntimeBinderException
【发布时间】:2014-12-19 03:13:44
【问题描述】:

我正在构建一个UITypeEditor(从属性网格启动)来编辑一个Dictionary<T,T>,其中T可以是任何标量类型(intlongdoublestringDateTime 等)。 将要编辑的字典作为名为 innerobjectobject 传递到控件中。我得到的类型和键值类型如下:

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;

稍后当我尝试为其添加值时,我执行以下操作(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;
}

此时抛出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.

【问题讨论】:

    标签: c# .net dynamic


    【解决方案1】:

    您还需要 ab 是动态的:

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

    【讨论】:

      猜你喜欢
      • 2011-07-04
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多