1

我正在尝试使用返回 bool 的方法验证文本的最大长度。

public bool ExceedsMaxLength(object value)
{
     if(this.MyPropertyType == typeof(String))
     {
           return ((string)value).Length > this.MaximumAllowed;
     }
     //Numeric?????
}

我试图在这个方法中做到这一点

if(this.MyPropertyType == typeof(Int16))
{
     return ((short)value > Int16.MaxValue);
}

我的方式正确吗?这没关系,我应该为任何数字数据类型执行此操作?或者还有另一种简化的方法可以使用.NET 的特殊方法来做到这一点?

谢谢!

4

1 回答 1

2

由于您提到您只对根据字符串表示限制最大长度感兴趣,因此以下代码将满足您的需要:

public bool IsOverMaximumLength(object value)
{
    return (value.ToString().Length > this.MaximumAllowed);
}

如果要检查多种数据类型的长度,更多方法或重载更合适:

public bool IsOverMaximumLengthForInt32(long value)
{
    return value > Int32.MaxValue;
}

public bool IsOverMaximumLengthForInt16(int value)
{
    return value > Int16.MaxValue;
}

这是一种反射方法,它也可能适合您的需求:

public static bool ExceedsMaximumValue(object source, object destination)
{
    Type sourceType = source.GetType();
    FieldInfo sourceMaxValue = sourceType.GetField("MaxValue");

    if (Object.ReferenceEquals(sourceMaxValue, null))
    {
        throw new ArgumentException("The source object type does not have a MaxValue field associated with it.");
    }

    Type destinationType = destination.GetType();
    FieldInfo destinationMaxValue = destinationType.GetField("MaxValue");

    if (Object.ReferenceEquals(destinationMaxValue, null))
    {
        throw new ArgumentException("The destination object type does not have a MaxValue field associated with it.");
    }

    object convertedSource;
    if (destinationType.IsAssignableFrom(sourceType))
    {
        convertedSource = source;
    }
    else
    {
        TypeConverter converter = TypeDescriptor.GetConverter(sourceType);
        if (converter.CanConvertTo(destinationType))
        {
            try
            {
                convertedSource = converter.ConvertTo(source, destinationType);
            }
            catch (OverflowException)
            {
                return true;
            }
        }
        else
        {
            throw new ArgumentException("The source object type cannot be converted to the destination object type.");
        }
    }

    Type convertedSourceType = convertedSource.GetType();

    Type[] comparisonMethodParameterTypes = new Type[1]
    {
        destinationType
    };

    MethodInfo comparisonMethod = convertedSourceType.GetMethod("CompareTo", comparisonMethodParameterTypes);
    if (Object.ReferenceEquals(comparisonMethod, null))
    {
        throw new ArgumentException("The source object type does not have a CompareTo method.");
    }

    object[] comparisonMethodParameters = new object[1]
    {
        destination
    };

    int comparisonResult = (int)comparisonMethod.Invoke(convertedSource, comparisonMethodParameters);

    if (comparisonResult > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
于 2013-11-05T21:20:29.563 回答