问题
I was using this code to populate a cell in a spreadsheet using EPPlus:
using (var footerMonth1Cell = prodUsageWorksheet.Cells[columnFooterRow, MONTH1_COL])
{
footerMonth1Cell.Value = monthsTruncatedYears[0];
footerMonth1Cell.Style.Font.Size = DATA_FONT_SIZE;
footerMonth1Cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
It was working fine, I thought, but a user complained that it was producing "green triangles" in the cells. "monthsTruncatedYears" is a generic list of string.
So I added this helper function:
public static void SetValueIntOrStr(this ExcelRangeBase range, object value)
{
string strVal = value.ToString();
if (!String.IsNullOrEmpty(strVal))
{
double dVal;
int iVal;
if (double.TryParse(strVal, out dVal))
range.Value = dVal;
else if (Int32.TryParse(strVal, out iVal))
range.Value = iVal;
else
range.Value = strVal;
}
else
range.Value = null;
}
...which I got from here, and then tried to refactor the original code to call that helper function like so:
using (var footerMonth1Cell = prodUsageWorksheet.Cells[columnFooterRow, MONTH1_COL])
{
footerMonth1Cell.Value = SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);
footerMonth1Cell.Style.Font.Size = DATA_FONT_SIZE;
footerMonth1Cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
However, it won't compile, telling me, "Cannot implicitly convert type 'void' to 'object'"
Since the second arg passed to SetValueIntOrStr(), namely "value", is of type object, I assume that is the problem. So why does the compiler apparently view monthsTruncatedYears[0] as being void? In the legacy code I assigned it as the value to the cell, and it wasn't void at that time, so...?!?
I tried casting the second arg to object like so:
footerMonth1Cell.Value = ReportRunnerConstsAndUtils.SetValueIntOrStr(footerMonth1Cell, object(monthsTruncatedYears[0]));
...but that won't compute, either, with "Invalid expression term 'object'"
...and this similar attempt:
footerMonth1Cell.Value = ReportRunnerConstsAndUtils.SetValueDoubleOrIntOrStr(footerMonth1Cell, monthsTruncatedYears[0] as object);
...elicits, "Cannot implicitly convert type 'void' to 'object'"
Note that the helper method is actually misnamed in the borrowed code; instead of "SetValueIntOrStr" it should be "SetValueDoubleOrIntOrStr"
回答1:
The problem is the line
footerMonth1Cell.Value = SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);
SetValueIntOrStr
does not return any value (void) and therefore cannot be used to assign a value to the footerMonth1Cell.Value
.
This would be valid code because the Value property is already changed inside the function:
SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);
来源:https://stackoverflow.com/questions/39417362/why-am-i-getting-cannot-implicitly-convert-type-void-to-object-with-this