如何将字符串类型转换为用户定义的自定义类型
我有一个字符串值需要转换为我的用户定义的自定义类型。如何做到这一点,请帮助我。如何将字符串类型转换为用户定义的自定义类型
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] };
}
}
当然,所提供的例子非常简单,但它至少不会让你开始。
你能举个例子吗? – Pradeep 2010-08-31 14:43:05
对于实际的转换,我们需要查看类结构。然而这个看起来为骨架如下:
class MyType
{
// Implementation ...
public MyType ConvertFromString(string value)
{
// Convert this from the string into your type
}
}
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));
没有办法知道这一点,因为它是用户定义的类型。 – 2010-08-31 14:44:30
首先,您需要定义一种您的类型在转换为字符串时将遵循的格式。 一个简单的例子是社会安全号码。你可以很容易地将其描述为正则表达式。
\d{3}-\d{2}-\d{4}
之后,你很简单,需要扭转过程。约定是为你的类型定义一个Parse
方法和TryParse
方法。区别在于TryParse
不会抛出异常。
public static SSN Parse(string input)
public static bool TryParse(string input, out SSN result)
现在,您按照实际解析输入字符串的过程可以像您希望的那样复杂或简单。通常,您会标记输入字符串并执行语法验证。 (EX:一个破折号可以去这里?)
number
dash
number
dash
number
这真的取决于你想要多少工作投入它。以下是如何标记字符串的基本示例。
private static IEnumerable<Token> 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;
}
}
你能发表一个你想要做的例子吗? – 2010-08-31 14:39:57
你能给一些代码片段样本吗? – 2010-08-31 14:40:17
你知道,它可能更模糊。 – Marc 2010-08-31 14:40:40