我有一个类
class PartitionTemplate
{
public PartitionTemplate()
{
keepLabels = new List<string>();
partitions = new List<partition>();
}
[JsonProperty("keepLabels")]
public List<String> keepLabels { get; set; }
[JsonProperty("slot")]
public int slot { get; set; }
....
}
我的目标是使用以下代码使用 propertyGrid
编辑它:
PartitionTemplate partiTemplate;
//fi is FileInfo with the class as json using
//Newtonsoft.Json.JsonConvert.DeserializeObject<PartitionTemplate>(File.ReadAllText(partitionfile.FullName));
PartitionTemplate.ReadOrCreatePartitonConfigurationFile(out partiTemplate, fi);
propertyGrid1.SelectedObject = partiTemplate;
我的问题是:当我尝试add
元素以keepLabels
时,出现以下错误:
Exception thrown: 'System.MissingMethodException' in mscorlib.dll
Additional information: Constructor on type 'System.String' not found.
如何修复?
发生这种情况
是因为当您单击集合编辑器(属性网格的标准编辑器(中的"添加"按钮时,它会使用假定的公共无参数构造函数创建一个新项,该构造函数在 System.String 中不存在(您无法执行var s = new String();
(。
但是,如果要保持keepLabels属性不变,则可以创建一个自定义编辑器,如下所示:
// decorate the property with this custom attribute
[Editor(typeof(StringListEditor), typeof(UITypeEditor))]
public List<String> keepLabels { get; set; }
....
// this is the code of a custom editor class
// note CollectionEditor needs a reference to System.Design.dll
public class StringListEditor : CollectionEditor
{
public StringListEditor(Type type)
: base(type)
{
}
// you can override the create instance and return whatever you like
protected override object CreateInstance(Type itemType)
{
if (itemType == typeof(string))
return string.Empty; // or anything else
return base.CreateInstance(itemType);
}
}