与えられた順序に従ってそのプロパティにいくつかの値を割り当てることになっているいくつかのコードがあります。
これがその仕事をするいくつかのサンプルコードです:
public class AnimalCount
{
public int Dogs;
public int Cats;
public int Fish;
public int Birds;
public void RankValues(string first, string second, string third, string fourth)
{
string property = "";
int value = -1;
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 0: property = first; value = 10; break;
case 1: property = second; value = 12; break;
case 2: property = third; value = 19; break;
case 3: property = fourth; value = 20; break;
}
switch (property)
{
case "dogs": Dogs = value; break;
case "cats": Cats = value; break;
case "fish": Fish = value; break;
case "birds": Birds = value; break;
}
}
}
}
ただし、このコードにはいくつかの問題があります。
コードに例外処理を入力するよりも良い解決策はありますか?私にはひどく醜いようです。
あなたが知っている必要がある場合、私はダンジョンズアンドドラゴンズで要求された能力スコアの順序を取り、選択した順序でそれらをロールする関数を書こうとしています。
私はこれをします:
public class AnimalCount
{
public int Dogs;
public int Cats;
public int Fish;
public int Birds;
private Dictionary<string, Action<int>> rankers
= new Dictionary<string, Action<int>>()
{
{ "dogs", v => Dogs = v },
{ "cats", v => Cats = v },
{ "fish", v => Fish = v },
{ "birds", v => Birds = v },
};
private Action<string, int> setRank = (t, v) =>
{
if (rankers.ContainsKey(t))
{
rankers[t](v);
}
};
public RankValues(string first, string second, string third, string fourth)
{
setRank(first, 10);
setRank(second, 12);
setRank(third, 19);
setRank(fourth, 20);
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加