gpt4 book ai didi

c# - 如何使用 Convert 将字符串转换为自定义对象

转载 作者:太空狗 更新时间:2023-10-29 23:28:48 26 4
gpt4 key购买 nike

我在 Programming in C# 一书中找到了以下语句:

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

我有课:

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

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

但是如何使用Convert into a对象来转换字符串呢?

更新:我知道解析的想法。但我的问题是如何使用 Convert 类从字符串创建新对象。

最佳答案

您可以提供 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;
}
}

示例:

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

关于c# - 如何使用 Convert 将字符串转换为自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46684848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com