我有这一段代码在C#:

private static void _constructRow(SqlDataReader reader, system.IO.StreamWriter stwr, bool getColumnName)
{
  for (int i = 0; i < reader.FieldCount; i++)
   stwr.Writeline(String.Format("<td>{0}</td"), getColumnName ? reader.GetName(i) : reader.GetValue(i).ToString()));
}

我想了解的是先从部分“getColumnName?”并用“的ToString()”的端部一样。我理解,这是一个System.Object类型,但我不知道它专门针对或它如何工作。 我想是因为这一点:“读者”在它有多个行,我想的WriteLine只有特定的行

如果有人能帮助我在任的,我会很感激。

有帮助吗?

解决方案

该函数迭代的所有列中的数据读取器,则对于每一个:

如果getColumnName返回true,它输出<td>标签之间的列的名称,数据的其它方式的值。

要取消构建体还:

reader.GetName(i) - this returns the name of the column

reader.GetValue(i).ToString() - this returns the value of the column as a string

getColumnName - a function the will return true if a column name can be gotten

?: - the conditional operator. If the expression before the ? is true, the expression to the left of the : is used, otherwise the one on the right

String.Format("<td>{0}</td", arg) - this will output "<td>arg</td>" (btw - your code is wrong, the ) should not be just after the first string)

其他提示

这是一个条件运算符。它说如果getColumnName为真,则使用reader.GetName(i)否则使用reader.GetValue(i).ToString()

的格式是这样的:

ThingToCheck ? UseIfCheckIsTrue : UseIfCheckIsFalse

在的代码,它看起来像getColumnName是的作为标题行,所以它的使用输出列名和再次调用了所有其它行的下,以输出的值。

这被称为条件运算。

的参数getColumnName被评估并且如果为真,则?后的第一个参数返回,如果否,则第二

所以,如果getColumnName == true,则将会看到<td>NAME</td>其他<td>Value</td>

有意义吗?

有以下等

if (getColumnName == true)
{
    reader.GetName(i); // GetName is string so no need to convert this in string I.E ToString()
}
else
{
    reader.GetValue(i).ToString(); // GetValue returns object so this needs to convert in string using .ToString()
}

由于getColumnName是布尔类型的因此没有必要对其进行测试样

If (getColumnName == true)

可以写为

If (getColumnName)

<强>的String.Format(字符串,方法)

在与给定对象指定的字符串

和的String.Format方法替换项,该方法具有两个参数第一个是串和第二个是对象。 例如

string.Format("Question number {0} is answered by {1} {2}", 11, "Adam", "Yesterday");

在出放将是

题号11由亚当回答昨天

正如你可以看到{0}被替换为11和{1}被替换为亚当和{2}被替换为昨天。

您可以阅读更多关于这个这里

这是三元运算时,使用如果为其他块的自组织结构。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top