如何为任何数据类型C#模拟一种maxlength

时间:2013-11-05 21:08:11

标签: c#

我正在尝试使用返回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特殊方法的简化方法吗?

谢谢!

1 个答案:

答案 0 :(得分: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;
    }
}