このコードのString.Formatのピースは何をするのでしょうか?
-
22-09-2019 - |
質問
私は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
がtrueの場合は、そうでないreader.GetName(i)
reader.GetValue(i).ToString()
を使用することを言います
形式は、この次のとおりです。
ThingToCheck ? UseIfCheckIsTrue : UseIfCheckIsFalse
getColumnName
であるように、はコードでは、見た目の真のヘッダー行のため、それが使用したカラム名を出力し、他のすべての行に対して再度呼ばれていますので、の偽を、出力します数値ます。
引数getColumnName
が評価され、真の場合はfalseの場合、?
後の最初の引数は、第二に返されます。
そうは、の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の方法置き換え項目は、この方法は、最初のものは文字列であり、第2の目的とする二つの引数を有します。 例えば
string.Format("Question number {0} is answered by {1} {2}", 11, "Adam", "Yesterday");
アウトプットは
質問数11は、昨日アダムによって答えている。
あなたが見ることができるように、{0} 11で置換されており、{1}はアダムで置換されており、{2}が昨日に置き換えられます。
あなたはこのここを
についての詳細を読むことができますこれは、使用三オペレータに、ありますもしelseブロックのアドホック構成するためます。