两个字符串的数据类型的平等比较值在C# [英] Equality comparison of the datatype of two strings value in C#

查看:159
本文介绍了两个字符串的数据类型的平等比较值在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个奇怪的要求。我知道甚至我的问题是很混乱。这是我想知道的。

This is a weird requirement I have. I know even my question is quite confusing. Here is what I want to know.

我有两个字符串变量。我需要对字符串变量中的基础值的数据类型进行相等比较。例如

I've two string variables. I need to do equality comparison of the datatype of the underlying value in the string variables. For ex.

string firstVariable = "123"; // It contains integer value. i.e. I can convert it to integer value
string secondVariable = "string" // It contains string value.

现在我需要比较这两个字符串的基础值的数据类型是否相同。我如何做到这一点?

Now I need to compare whether datatype of the underlying values of these two strings are same. How can I do this?

更新:感谢所有的澄清和答案。如果我知道一个变量的类型怎么样?
例如:

Update: Thanks to all for the clarifications and answers. How about if I know the type of one variable? For ex:

int firstVariable;
string secondVariable = "123". 

这可以检查第一个变量的类型是否等于secondVariable的转换值。当我将firstVariable声明为 int 时,并不意味着它总是 int 类型。我的意思是,我知道一个变量的类型和其他变量是字符串,我想比较第一变量的数据类型和第二变量的值数据类型的数据类型。

Is this possible to check whether the type of the first variable equals to converted value of the secondVariable. When I declared firstVariable as int it doesn't mean it is always int type. What I mean here is, I know the type of one variable and other variable is string and I want compare equality of the datatypes of firstvariable and value datatype of the secondVariable.

Convert.ChangeType 会在上述情况下帮助吗?

Is Convert.ChangeType will anyway help in the above scenario?

我知道这是一个愚蠢的问题,

I know this is silly question, but out of curiosity in the language feature exploring, I wanted to know this.

推荐答案

从我的头开始,所以可能会:

Written from my head so there may (will) be errors:

class StringTypeEqualityComparer : IEqualityComparer<string, string>
{
    public bool Equals(string x, string y)
    {
        int tempInt;
        if (Int32.TryParse(x, out tempInt) && (Int32.TryParse(y, out tempInt))
            return true;

        bool tempBool;
        if (Boolean.TryParse(x, out tempBool) && Boolean.TryParse(y, out tempBool))
            return true;

        float tempFloat;
        if (Single.TryParse(x, out tempFloat) && Single.TryParse(y, out tempFloat))
            return true;

        // And whatever other types you want to compare...

        return false;

        // But what if two regular strings should also evaluate to equal?
    }
}

这篇关于两个字符串的数据类型的平等比较值在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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