如何将字符串类型转换为用户定义的自定义类型

我有一个字符串值需要转换为我的用户定义的自定义类型。 怎么做,请帮帮我。

public class ItemMaster { public static ItemMaster loadFromReader(string oReader) { return oReader;//here i am unable to convert into ItemMaster type } } 

根据您的类型,您可以通过两种方式进行操作。

第一种是在类型中添加一个带有String参数的构造函数。

 public YourCustomType(string data) { // use data to populate the fields of your object } 

第二个是添加静态Parse方法。

 public static YourCustomType Parse(string input) { // parse the string into the parameters you need return new YourCustomType(some, parameters); } 

在用户定义的自定义类型上创建Parse方法:

 public class MyCustomType { public int A { get; private set; } public int B { get; private set; } public static MyCustomType Parse(string s) { // Manipulate s and construct a new instance of MyCustomType var vals = s.Split(new char[] { '|' }) .Select(i => int.Parse(i)) .ToArray(); if(vals.Length != 2) throw new FormatException("Invalid format."); return new MyCustomType { A = vals[0], B = vals[1] }; } } 

当然,提供的示例非常简单,但它至少可以帮助您入门。

Convert.ChangeType()方法可以帮到你。

 string sAge = "23"; int iAge = (int)Convert.ChangeType(sAge, typeof(int)); string sDate = "01.01.2010"; DateTime dDate = (DateTime)Convert.ChangeType(sDate, typeof(DateTime)); 

首先,您需要定义类型在转换为字符串时将遵循的格式。 一个简单的例子是社会安全号码。 您可以轻松地将其描述为正则表达式。

 \d{3}-\d{2}-\d{4} 

之后,您只需要反转该过程。 惯例是为您的类型定义Parse方法和TryParse方法。 区别在于TryParse不会抛出exception。

 public static SSN Parse(string input) public static bool TryParse(string input, out SSN result) 

现在,您实际解析输入字符串的过程可以像您希望的那样复杂或简单。 通常,您会将输入字符串标记化并执行语法validation。 (EX:可以冲到这里吗?)

 number dash number dash number 

这实际上取决于你想要投入多少工作。 以下是如何标记字符串的基本示例。

 private static IEnumerable Tokenize(string input) { var startIndex = 0; var endIndex = 0; while (endIndex < input.Length) { if (char.IsDigit(input[endIndex])) { while (char.IsDigit(input[++endIndex])); var value = input.SubString(startIndex, endIndex - startIndex); yield return new Token(value, TokenType.Number); } else if (input[endIndex] == '-') { yield return new Token("-", TokenType.Dash); } else { yield return new Token(input[endIndex].ToString(), TokenType.Error); } startIndex = ++endIndex; } } 

对于实际转换,我们需要查看类结构。 然而,这个骨架看起来如下:

 class MyType { // Implementation ... public MyType ConvertFromString(string value) { // Convert this from the string into your type } }