我如何能够发现字符串值的数据类型 [英] How Do I Can Discovery Datatype Of A String Value

查看:80
本文介绍了我如何能够发现字符串值的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



a有一个字符串,我需要知道你的价值是多少。我该怎么办?



Hello guys,

a have a string and i need to know if your value is a number. how i can do this?

string myString = "1";
//is a string but your value is a number.





谢谢



thanks

推荐答案

你必须检查值是否可以解释为布尔值或整数或其他...

http: //msdn.microsoft.com/en-us/library/system.boolean.tryparse(v=vs.110).aspx [ ^ ]

http://msdn.microsoft.com/en-us/library/system。 int32.tryparse(v = vs.110).aspx [ ^ ]

http://msdn.microsoft.com/en-us/library/system.double.tryparse(v = vs.110).aspx [ ^ ]
You have to check if value can be interpreted as Boolean or Integer or other...
http://msdn.microsoft.com/en-us/library/system.boolean.tryparse(v=vs.110).aspx[^]
http://msdn.microsoft.com/en-us/library/system.int32.tryparse(v=vs.110).aspx[^]
http://msdn.microsoft.com/en-us/library/system.double.tryparse(v=vs.110).aspx[^]


离开我的头顶,你总是可以实现蛮力的方法来测试字符串条目 - 我刚刚在记事本中敲了这个但是理论是合理的:
Off the top of my head, you could always implement the brute force approach to testing the string entry - I've just knocked this up in Notepad but the theory is sound:
public static class ConverterExtensions
{
  public static bool IsNumber(this string source)
  {
    if (string.IsNullOrWhitespace(source)) return false;

    const Types[] types = new Type[]{ 
      typeof(short), typeof(ushort), 
      typeof(int), typeof(uint), 
      typeof(long), typeof(ulong), 
      typeof(float), typeof(double), typeof(decimal)
    };
    foreach (Type type in types)
    {
      if (source.TryChangeType(type))
        return true;
    }
    return false;
  }

  public static bool TryChangeType(this string source, Type targetType)
  {
    try
    {
      Convert.ChangeType(source, targetType);
      return true;
    }
    catch (Exception)
    {
      return false;
    }
  }
}


string myString = "1";
int intVal = 0;
if(int.TryParse(myString, out intVal))
{

}







int.TryParse 

将返回true。


这篇关于我如何能够发现字符串值的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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