How to convert a string to a custom object using Convert

I found the following instruction in a Programming in C#book:

IFormattable provides functionality to format the value of an object into a string representation. It is also used by the Convert class to do the opposite.

I have a class:

class a : IFormattable
{
    private string aa = "123";
    private int bb = 5;

    public string ToString(string format, IFormatProvider formatProvider)
    {
        return $"aa={aa} bb={bb}" ;
    }
}

But how to convert a string using Convert to an object a?

UPD: I know the idea of ​​parsing. But my question is how to use the Convert class to create a new object from a string.

+4
source share
2 answers

You can provide an explicit conversion operator:

public class A : IFormattable
{
    public string Aa { get; } = "123";
    public int Bb { get; } = 5;

    public A(){ }

    public A(string aa, int bb)
    {
        this.Aa = aa;
        this.Bb = bb;
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        return $"aa={Aa} bb={Bb}";
    }

    public static explicit operator A(string strA)  
    {
        if (strA == null) return null;
        if (!strA.Contains("aa=") || !strA.Contains(" bb=")) return null;
        string[] parts = strA.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length != 2 || !parts[0].StartsWith("aa=") || !parts[1].StartsWith("bb=")) return null;

        string aa = parts[0].Substring(3);
        string bb = parts[1].Substring(3);
        int bbInt;
        if (!int.TryParse(bb, out bbInt)) return null;
        A a = new A(aa, bbInt);
        return a;
    }
}

Example:

A a = new A("987", 4711);
string toString = a.ToString(null, null);
a = (A) toString;
+2
source

See below answer.

, . , , .

implicit explicit :

public class A
{
   public static implicit operator string(A a)
   {
      // allows: 
      // var a = new A();
      // string x = a;
      return "A converted to string"; 
   } 

   public static explicit operator A(string s)
   {
      // allows: 
      // var s = "something";
      // var a = (A)s;
      return new A(); 
   } 
}

. . , , .

Convert.ChangeType. IConvertible, switch . (. ). , TypeCode, , Enums , IConvertible.GetTypeCode. :

var d = (decimal)System.Convert.ChangeType("17.4", typeof(decimal));

, :

static TTargetType ParseTo<TTargetType>(string target)
{
   return (TTargetType)System.Convert.ChangeType(target, typeof(TTargetType));
}

:

var d = ParseTo<decimal>("17.4");

, :

var d = decimal.Parse("17.4");
+1

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


All Articles