CollectionEditor产生“对象与目标类型不匹配”。对于System.Drawing.Point。我有一个自定义控件,其属性类型是Collection。当我使用CollectionEditor编辑此属性时,CollectionEditor窗口显示“对象与目标类型不匹配”。对于“X”和“Y”属性。但是,如果我使用System.Drawing.PointF,则不会出现故障。谁能解释为什么会出现这种差异?Point和PointF之间的区别真正在于PointConverter。为什么这会导致问题是一个很长的故事,但归根结底可以归结为以下几点:这。根据上述ICustomTypeDescriptor接口方法的MSDN页面,实现应该返回一个包含由指定属性描述符描述的属性的对象。如果我理解正确,在这种情况下,实现与文档相矛盾。这是基于我自己的一些研究,所以不要想当然。我在MicrosoftConnect上发布了关于此问题的报告,因此希望我们能在几天内确定。收到回复后我会报告。我不是.NET/C#专家,但问题似乎出在PointConverter类中,该类用作System.Drawing.Point类的TypeConverterAttribute。集合编辑器必须使用失败的PointConverter类中的内容。我怀疑PointConverter因为PointF类没有TypeConverterAttribute,它工作正常。在下面的示例中,我使用MSDN中的一些代码拼凑而成,在集合中使用Point类以及将MyPoint类与自定义TypeConverter一起使用时会出现问题。使用系统;使用System.Collections.Generic;使用System.ComponentModel;使用系统绘图;使用系统数据;使用系统文本;使用System.Windows.Forms;使用System.Globalization;namespaceWindowsControlLibrary1{publicclassMyTypeConverter:TypeConverter{//覆盖TypeConverter的CanConvertFrom方法。//ITypeDescriptorContext接口为//转换提供上下文。通常,此接口在设计时用于//提供有关设计时容器的信息。publicoverrideboolCanConvertFrom(ITypeDescriptorContextcontext,TypesourceType){if(sourceType==typeof(string)){返回真;}returnbase.CanConvertFrom(context,sourceType);}//重写TypeConverter的ConvertFrom方法。publicoverrideobjectConvertFrom(ITypeDescriptorContextcontext,CultureInfoculture,objectvalue){if(valueisstring){string[]v=((string)value).Split(newchar[]{','});}返回newMyPoint(int.Parse(v[0]),int.Parse(v[1]));}returnbase.ConvertFrom(context,culture,value);}//重写TypeConverter的ConvertTo方法。publicoverrideobjectConvertTo(ITypeDescriptorContextcontext,CultureInfoculture,objectvalue,TypedestinationType){if(destinationType==typeof(string)){return((MyPoint)value).X+","+((MyPoint)value).}是;}returnbase.ConvertTo(context,culture,value,destinationType);}}[SerializableAttribute][TypeConverterAttribute(typeof(MyTypeConverter))]publicstructMyPoint{privateintx;私人整数y;publicMyPoint(int_x,int_y){x=_x;y=_y;}publicintX{get{返回x;}设置{x=值;}}publicintY{get{返回y;}设置{y=值;}}}publicpartialclassUserControl1:UserControl{privateListpoints;私有列表点;私人列表我的积分;publicListPointList{get{returnpoints;}set{points=value;}}publicListPointFList{get{returnpointfs;}set{pointfs=value;}}publicListMyPointList{get{returnmypoints;}设置{mypoints=value;}}publicUserControl1(){InitializeComponent();我的解决方案是使用collectioneditor(Point)编辑列表之前,使用TypeDescriptor.AddAttributes(GetType(Drawing.Point),NewTypeConverterAttribute())将Point的类型转换器设置为null,然后使用TypeDescriptor.AddAttributes(GetType(Drawing.Point),NewTypeConverterAttribute(GetType(PointConverter)))设置typeconverter为默认值以上是C#学习教程:CollectionEditor产生“对象与目标类型不匹配”。对于System.Drawing.Point。分享的所有内容,如果对大家有用,需要进一步了解C#学习教程,希望大家多加关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
