Nik*_*ola -2 c# string decimal converter
有没有办法实现这个目标?
我试过了:
string str = "{34.10,0,0.00}"; //the string as I get it from Postgres DB
decimal[] won;
won = (decimal[])(str); //Cannot convert type 'string' to 'decimal[]'
Run Code Online (Sandbox Code Playgroud)
我理想的是要进入won:
won[0] = 34.10
won[1] = 0
won[2] = 0.00
Run Code Online (Sandbox Code Playgroud)
当然,我可以用逗号分开,把它放在数组中,但我想知道是否有更好的方法.
你必须 Split
won = str.Trim('{', '}').Split(',').Select(decimal.Parse).ToArray();
Run Code Online (Sandbox Code Playgroud)
编辑:这部分只是为了好玩
无法decimal[]直接将字符串转换为数组,但如果需要,可以添加小数包装类并定义隐式转换:
class MyDecimal
{
private decimal[] _values;
public MyDecimal(int size)
{
_values = new decimal[size];
}
public decimal this[int index]
{
get { return _values[index]; }
set { _values[index] = value; }
}
public static implicit operator MyDecimal(string str)
{
var numbers = str.Trim('{', '}').Split(',');
MyDecimal d = new MyDecimal(numbers.Length);
d._values = numbers
.Select(x => decimal.Parse(x,CultureInfo.InvariantCulture))
.ToArray();
return d;
}
public static implicit operator string(MyDecimal md)
{
return string.Join(",", md._values);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
string str = "{34.10,0,0.00}"; //the string as I get it from Postgres DB
MyDecimal won = str;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1266 次 |
| 最近记录: |