1

我在 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 类型,但我不知道它具体做什么或它是如何工作的。因为这个,我想要那个:“阅读器”中有多行,我想只写特定的行。

如果有人可以在其中任何一个方面帮助我,我将不胜感激。

4

5 回答 5

3

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

格式是这样的:

ThingToCheck ? UseIfCheckIsTrue : UseIfCheckIsFalse

在代码中,标题行看起来getColumnNametrue,因此它输出列名并使用false再次调用所有其他行,以输出值。

于 2010-03-28T11:38:25.500 回答
2

该函数遍历数据读取器中的所有列,然后对每一列:

如果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)
于 2010-03-28T11:38:31.610 回答
0

这称为条件运算符。

对参数getColumnName进行评估,如果为真,?则返回后面的第一个参数,如果为假,则返回第二个。

所以,如果 getColumnName==true,你会看到<td>NAME</td>别的<td>Value</td>

有道理?

于 2010-03-28T11:39:01.220 回答
0

就像以下

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 是 bool 类型,所以不需要像这样测试它

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} 被替换为 Adam,{2} 被替换为 Yesterday。

您可以在此处阅读有关此内容的更多信息

于 2010-03-28T11:46:53.857 回答
0

这是三元运算符,用于 if else 块的临时构成。

于 2010-03-28T14:43:13.067 回答