如何使用自定义Converter解析CS1503

时间:2016-06-15 14:43:34

标签: c# .net winforms types

我在c#中有以下类/类型,我需要使用它来获得像Point这样但具有不同功能的东西。

[TypeConverter(typeof(KnotenConverter))]
class Knoten
{
    int x, y;
    List<Knoten> neighbors;


    #region gettersetter
    //Standard getter and setter here

    #endregion

    public bool hasNeighbors()
    {
        return Neighbors.Count > 0;
    }

    class KnotenConverter : TypeConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(Point)) return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            Knoten from = (Knoten)value;
            if (destinationType == typeof(Point))
            {
                return new Point(from.X, from.Y);
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }

    }

使用Knoten作为Point我实现了自己的TypeConverter,以便将Knoten转换为Point。但我一直在

  

CS1503 Argument&#39; 2&#39;无法从GridCalcer.Knoten转换为System.Drawing.Point。

我做错了什么?如何解决这个错误,以便它可以将我的Knoten转换为Point&#34;本身&#34;?

1 个答案:

答案 0 :(得分:1)

TypeConverter与编译时间没有任何共同之处。编译器错误表示您尝试将Knoten实例传递给期望Point的方法。为了能够做到这一点,您需要声明implicit转换运算符:

class Knoten
{
    // ...

    public static implicit operator Point(Knoten source)
    {
        return new Point(source.X, source.Y);
    }
}