C#尝试从类型列表中强制转换字符串

Kyu*_*u96 3 c# types casting

所以我有两个长度相等的列表,一个字符串列表和一个类型列表。由于要验证字符串是否可以转换为第二个列表中指定的相应类型。如果这不可能,我想抛出一个异常。

因此,想象一下这样的事情:

var strings = new List<string>(){"hi","123","542342342424423","5.1"};
var types = new List<Types>(){typeof(string),typeof(int),typeof(long),typeof(double)};
Run Code Online (Sandbox Code Playgroud)

所以我想检查一下:

hi can be converted to a string
123 can be converted to an int
542342342424423 can be converted to a long
5.1 can be converted to a double
Run Code Online (Sandbox Code Playgroud)

我以为是这样的:

hi can be converted to a string
123 can be converted to an int
542342342424423 can be converted to a long
5.1 can be converted to a double
Run Code Online (Sandbox Code Playgroud)

但是,这@type不是一个常量表达式,因此不起作用。我不一定需要强制转换值,如果它们可以转换或不转换,我只需要验证(是/否)。我该如何解决?

Bru*_*ndo 5

在C#中,字符串不等同于其类型(例如,与javascript比较)。如果想知道是否可以将字符串强制转换为int,则必须调用int.TryParse()并查看其是否成功。

这意味着您可能无法概括您期望的方式。

编辑:

我编写了一种通用的方法,只要您可以为可能遇到的每种类型定义一个方法

     var strings = new List<string>(){/* whatever strings */};
     var typeTesters = new List<Func<string, bool>>
     {
         text => int.TryParse(text, out _),
         text => double.TryParse(text, out _),
         text => long.TryParse(text, out _),
     };

     for (var index = 0; index < 4; index++)
     {
         var str = strings[index];
         var tester = typeTesters[index];

         // Attempt something like this
         if (!tester(str))
             throw new Exception();
     }
Run Code Online (Sandbox Code Playgroud)

如其他答案中给出的那样,您可以使用Convert.ChangeType为每种基本类型提供通用测试,并为自定义类型提供自己的函数。

  • `Convert.ChangeType`可以和`DateTime`一起使用。它可以与任何实现“ IConvertible”的东西一起使用。 (2认同)