如何动态解析和比较C#中的字符串值? [英] How to dynamically parse and compare string values in C#?

查看:191
本文介绍了如何动态解析和比较C#中的字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,我不得不重新编辑此问题。

Sorry that I had to re-edit this question.

我需要动态解析两个字符串值到相应的类型,并比较它们,然后返回一个bool结果。

I need to dynamically parse two string values to the appropriate type and compare them, then return a bool result.

示例1:

string lhs = "10";
string rhs = "10";

Compare.DoesEqual(lhs, rhs, typeof(int)); //true
Compare.DoesEqual(lhs, rhs, typeof(string)); //true

示例2:

string lhs = "2.0";
string rhs = "3.1";

Compare.IsGreaterThan(lhs, rhs, typeof(int)); //false
Compare.IsGreaterThan(lhs, rhs, typeof(double)); //false
Compare.IsGreaterThan(lhs, rhs, typeof(string)); //invalid, always false

目前我在做这样的事情方式):

Currently I am doing like this (I think it's stupid to do it such way):

public partial class Comparer
{
    public static bool DoesEqual(string lhs, string rhs, Type type)
    {
        if (type.Equals(typeof(int)))
        {
            try
            {
                return int.Parse(lhs) > int.Parse(rhs);
            }
            catch
            {
                return false;
            }
        }

        if (type.Equals(typeof(double)))
        {
            try
            {
                return double.Parse(lhs) > double.Parse(rhs);
            }
            catch
            {
                return false;
            }
        }

        return false;
    }
}


public partial class Comparer
{
    public static bool IsGreaterThan(string lhs, string rhs, Type type)
    {
        if (type.Equals(typeof(int)))
        {
            try
            {
                return int.Parse(lhs) == int.Parse(rhs);
            }
            catch
            {
                return false;
            }
        }

        if (type.Equals(typeof(double)))
        {
            try
            {
                return double.Parse(lhs) == double.Parse(rhs);
            }
            catch
            {
                return false;
            }
        }

        if (type.Equals(typeof(string)))
        {
            return lhs.Equals(rhs);
        }

        return false;
    }
}

我在寻找更好的)实现(可能使用表达式树?)。我欣赏任何建议。谢谢!

I am looking for better a better (more generic way) implementation (perhaps using Expression Tree?). I appreciate any suggestions. Thank you!

推荐答案

最通用的方法是使用 TypeConverter 。让我们假设我们有:

The most generic way is to use TypeConverter. Let's say we have:

string rhs = ...;
string lhs = ...;
Type type = ...;

。您可以:

TypeConverter conv = TypeDescriptor.GetConverter(type);
try
{
    object rho = conv.ConvertFrom(rhs);
    object lho = conv.ConvertFrom(lhs);
    ...
}
catch (NotSupportedException)
{
   // No luck - couldn't parse the string
}

不幸的是,处理时没有办法避免 catch 转换器。现在你有两个对象从字符串中解析,你可以做通用的比较。平等很简单 - 只需使用 Object.Equals (最好是静态的 - 它处理null):

Unfortunately, there's no way to avoid a catch there when dealing with converters. Now that you have two objects parsed from strings, you can do generic comparisons. Equality is simple - just use Object.Equals (preferably static one - it handles nulls):

if (Object.Equals(rho, lho))
{
    ...
}

对于排序比较,您可以检查类型是否支持 IComparable

For ordering comparisons, you can check if the type supports IComparable:

IComparable rhc = rho as IComparable;
if (rhc != null && rhc.CompareTo(lho) < 0) // rhs less than lhs
{ 
    ...
}

注意,有些类型不提供运算符< 仍然是有序的,因此实现 IComparable - 例如 String

Note however that some types that don't provide operator< are still ordered, and thus implement IComparable - for example, String does that.

这篇关于如何动态解析和比较C#中的字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆