我有一个班级
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.
怎么修好?
答案 0 :(得分:1)
这是因为当您单击Collection Editor(属性网格的标准编辑器)中的“添加”按钮时,它会使用假定的公共无参数构造函数创建一个新项目,该构造函数在System上不存在。字符串(你不能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);
}
}