以下可以为空的十进制代码已触发重载方法错误:
decimal? t1 = null;
decimal? t2 = null;
decimal? t3 = null;
decimal res = 0;
decimal tt1 = 0;
decimal tt2 = 0;
decimal tt3 = 0;
if (decimal.TryParse(textBox1.Text, out tt1))
t1 = tt1;
if (decimal.TryParse(textBox2.Text, out tt2))
t2 = tt2;
if (decimal.TryParse(textBox3.Text, out tt3))
t3 = tt3;
res = Math.Abs(t1 + t2 - t3);
textBox4.Text = res.ToString();
上面的代码建议在三个textBox和第四个textBox之间进行计算,显示它们的结果。但问题是可空类型十进制不支持Math.Abs方法。怎么克服?如何克服意味着我想通过另一种方式在Math.Abs方法中允许为空。
答案 0 :(得分:2)
您应该执行空检查,但代码为:
res = Math.Abs((decimal)t1 + (decimal)t2 - (decimal)t3);
或者:
res = Math.Abs(t1.Value + t2.Value - t3.Value);
答案 1 :(得分:1)
我的猜测是你实际上想要Math.Abs(tt1 + tt2 - tt3)
。
如果您确实希望在任何输入为null
时返回null
,那么您可能想要这样的内容:
decimal? res = t1 + t2 - t3;
if (res != null)
res = Math.Abs(res.Value);
textBox4.Text = res.ToString();
答案 2 :(得分:1)
仔细阅读了你的例子后,我认为这是一个人为的例子,因为设置t1,t2或t3的唯一原因是给出了证明问题的机会。因此,我将我的榜样改写为希望更符合你意图的事情。
private void button1_Click(object sender, EventArgs e)
{
//Read some values in a contrived example to get a mixture of null
//and not null values into t1, t2 & t3
decimal? t1 = null;
decimal? t2 = null;
decimal? t3 = null;
decimal res = 0;
decimal tt1 = 0;
decimal tt2 = 0;
decimal tt3 = 0;
if (decimal.TryParse(textBox1.Text, out tt1))
t1 = tt1;
if (decimal.TryParse(textBox2.Text, out tt2))
t2 = tt2;
if (decimal.TryParse(textBox3.Text, out tt3))
t3 = tt3;
//We have setup our inputs now, so lets get down to how to handle the problem
//now. This should probably be in a separate function, but we are in a _Click
//method, so I am assuming we are overlooking such things in this example...
//return without setting textBox4 if any of t1, t2 & t3 are null
if (!t1.HasValue || !t2.HasValue || !t2.HasValue)
{
return;
}
//1, 2 & 3 are all valid, so set textBox4
res = Math.Abs(t1.Value + t2.Value - t3.Value);
textBox4.Text = res.ToString();
}
这里的要点是我们应该明确指出,当3个输入中的任何一个为null时,textBox4不会被设置,而不是从Math.Abs()的返回中推断出这个,并且还可以使用可空的Value属性键入而不是转换为值类型,我更喜欢风格..
答案 3 :(得分:0)
这样的事情怎么样?
decimal? a = 4;
decimal? b = 3.254m;
decimal? c = 9.765675m;
decimal? d = (a + b - c);
decimal? res = null;
if (d != null)
{
res = Math.Abs((decimal)d);
}
textBox4.Text = (res != null) ? res.ToString() : "null";
答案 4 :(得分:0)
如果将null传递给Math.Abs,您会得到什么结果?但您可能希望使用空合并运算符??。
res = Math.Abs(()??0);
之后的值???是前面的表达式为null时使用的备用值。 所以如果Abs的参数为null,你想得到null吗?
Decimal? temp=t1 + t2 - t3;
if(temp!=null)
temp=Math.Abs(temp.Value);
textBox4.Text = temp.ToString();
答案 5 :(得分:0)
以上问题的精确解决方案是: -
private void button1_Click(object sender, EventArgs e)
{
decimal? t1 = null;
decimal? t2 = null;
decimal? t3 = null;
decimal tt1 = 0;
decimal tt2 = 0;
decimal tt3 = 0;
if (decimal.TryParse(textBox1.Text, out tt1))
t1 = tt1;
if (decimal.TryParse(textBox2.Text, out tt2))
t2 = tt2;
if (decimal.TryParse(textBox3.Text, out tt3))
t3 = tt3;
decimal? res = t1 + t2 - t3;
if (res != null)
{
res = Math.Abs((decimal) res);
}
textBox4.Text = res.ToString();
}
请参阅此代码不会抛出任何错误并清除使用Math.Abs()方法时可以出现的可空问题。