How to convert a string type to a custom user type

I have a string value that needs to be converted to my custom custom type. how to do this, please help me.

public class ItemMaster
{
    public static ItemMaster loadFromReader(string oReader)
    {
        return oReader;//here i am unable to convert into ItemMaster type
    }
}
-1
source share
5 answers

There are two ways to do this, depending on your type.

The first one adds a constructor to your type, which takes a parameter String.

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

The second adds a static method Parse.

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

Create a Parse method in a custom user type:

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] };            
    }
}

Of course, the above example is extremely simple, but at least you will start.

+2
source

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));
+1

, . . .

\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;
    }
}
+1
source

For the actual conversion, we will need to see the structure of the class. The skeleton for this would look like this:

class MyType
{
    // Implementation ...

    public MyType ConvertFromString(string value)
    {
        // Convert this from the string into your type
    }
}
0
source

Source: https://habr.com/ru/post/1687298/


All Articles