通用类拆箱错误

时间:2016-02-26 23:38:55

标签: c# generics

我有一个允许我设置最小和最大限制值的类。如果超出这些限制,则修改该值。直到现在我只使用双数据类型,但我也想使用整数。我希望通用类可以提供正确的解决方案,但我遇到了一些问题......

/// <summary>
/// This method takes a default value with the min and max limits. If the value exceeds these limits it is corrected.
/// </summary>
public partial class GeneratorProperty<T>
{
    private T _value;

    private T Min { get; }

    private T Max { get; }

    /// <summary>
    /// </summary>
    /// <param name="defaultValue"></param>
    /// <param name="min"></param>
    /// <param name="max"></param>
    public GeneratorProperty(T defaultValue, T min, T max)
    {
        _value = defaultValue;
        Min = min;
        Max = max;
    }

    /// <summary>
    /// </summary>
    public T Value
    {
        get { return _value; }
        set
        {
            if (typeof (T) == typeof (double))
            {
                var temp = (double)(object)value;
                (double)(object)_value = temp.ConstrainDouble((double)(object)Min, (double)(object)Max);
                //Cannot modify the result of an unboxing conversion
            }
            else if (typeof(T) == typeof(int))
            {
                var temp = (int)(object)value;
                (int)(object)_value = temp.ConstrainInt((int)(object)Min, (int)(object)Max);
                //Cannot modify the result of an unboxing conversion
            }
        }
    }
}

/// <summary>
/// </summary>
public static class Extention
{
    /// <summary>
    ///     The extension method Constrains a double using a min and max value.
    /// </summary>
    /// <param name="value">Value to test</param>
    /// <param name="min">minimum limit</param>
    /// <param name="max">maximum limit</param>
    /// <returns></returns>
    public static double ConstrainDouble(this double value, double min, double max)
    {
        if (value >= min && value <= max)
            return value;
        if (value >= max)
            return max;
        if (value <= min)
            return min;
        return 1;
    }

    public static double ConstrainInt(this int value, int min, int max)
    {
        if (value >= min && value <= max)
            return value;
        if (value >= max)
            return max;
        if (value <= min)
            return min;
        return 1;
    }
}

在设置T值期间,我想根据数据类型进行约束。但是,转换为正确的数据类型会给我带来问题吗?说实话,我对泛型很新。

对于如何解决这个问题,有什么建议或更好的方法?

1 个答案:

答案 0 :(得分:7)

每当你对泛型类型进行特定类型检查时(即if(typeof(T)== typeof(double)))你可能做错了。

public partial class GeneratorProperty<T> where T: IComparable<T>
{
    ...
    public T Value
    {
        get {... }
        set 
        {
            if (this.Max.CompareTo(value) < 0)
                this._value = this.Max;
            else if (this.Min.CompareTo(value) > 0)
                this._value = this.Min;
            else
                this._value = value;
        }
    }
}

泛型的主要目的之一是避免关心您实际接收和操作的类型。约束通过指定必须具有的类型部分来帮助缩小范围,以使其正常工作。

在这种情况下,您希望能够比较它们,因此在约束中强制执行。

相关问题