从“双”到“ System.Runtime.Serialization.ISerializable”的装箱转换

时间:2019-06-20 15:53:42

标签: c# generics xml-serialization boxing

我想序列化类Range<T>,所以我在其上实现ISerializable,如下所示:

public class Range<T> where T : IComparable<T>, ISerializable
{
    /// <summary>Minimum value of the range.</summary>
    public T Minimum { get; set; }

    /// <summary>Maximum value of the range.</summary>
    public T Maximum { get; set; }

    /// <summary>Presents the Range in readable format.</summary>
    /// <returns>String representation of the Range</returns>
    public override string ToString()
    {
        return string.Format("[{0} - {1}]", Minimum, Maximum);
    }

    /// <summary>Determines if the range is valid.</summary>
    /// <returns>True if range is valid, else false</returns>
    public bool IsValid()
    {
        return Minimum.CompareTo(Maximum) <= 0;
    }

    public XmlSchema GetSchema() { return null; }

    public void ReadXml(XmlReader reader)
    {
        // start reading
        reader.MoveToContent();

        Type t = typeof(T);
        var min = reader["Minimum"];
        var max = reader["Maximum"];

        Minimum = (T)Convert.ChangeType(min, t);
        Maximum = (T)Convert.ChangeType(max, t);

        reader.Read();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("Minimum", Minimum.ToString());
        writer.WriteAttributeString("Maximum", Maximum.ToString());
    }
}

但是当我想如下使用此类时,

public Range<double> Whr;

我收到此错误

严重性代码描述项目文件行抑制状态 错误CS0315类型'double'不能用作通用类型或方法'Range'中的类型参数'T'。没有从“双”到“ System.Runtime.Serialization.ISerializable”的装箱转换。 XCLASS ... \ ACLASS.cs 89有效

如何解决此错误?

1 个答案:

答案 0 :(得分:2)

我想你想要

public class Range<T> : ISerializable where T : IComparable<T>

您现在拥有的方式T必须实现ISerializable。您希望 class 代替实现ISerializable