![](/img/trans.png)
[英]Convert the user defined type to string and string to user defined type
[英]How to convert string type to user defined custom type
我有一个字符串值,需要将其转换为用户定义的自定义类型。 怎么做,请帮帮我。
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
不会引发异常。
public static SSN Parse(string input)
public static bool TryParse(string input, out SSN result)
现在,您实际解析输入字符串所遵循的过程可以像您希望的那样复杂或简单。 通常,您将标记输入字符串并执行语法验证。 (例如:可以在这里破折号吗?)
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;
}
}
对于实际的转换,我们需要查看其类结构。 但是,其骨架如下所示:
class MyType
{
// Implementation ...
public MyType ConvertFromString(string value)
{
// Convert this from the string into your type
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.