このコードのString.Formatのピースは何をするのでしょうか?

StackOverflow https://stackoverflow.com/questions/2532719

  •  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ブロックのアドホック構成するためます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top