私は 2 つの辞書を持っています。1 つはホストとして持っているファイル転送用で、もう 1 つはクライアントとして持っているファイル転送用です。
プログラムの領域の 1 つで実行しているコードは、これらの項目のいずれかを参照することを除いて、まったく同じです。このため、可能であればコードの重複を防止しようとしています。
public void UpdateFileTransferItems(FileTransferItem.FileTransferRole role)
{
// If the role is Sender then the variable is fileTransferSessionsAsHost, otherwise it is fileTransferSessionsAsClient.
var fileTransferSessions = role == FileTransferItem.FileTransferRole.Sender ? fileTransferSessionsAsHost : fileTransferSessionsAsClient;
foreach (var hostSession in fileTransferSessions)
{
Do Work in here.
}
}
明らかに三項演算子は機能しませんが、私がしようとしていることを実行するコードを作成するにはどうすればよいでしょうか? ロールが送信者の場合、変数を への参照にしたいのですがfileTransferSessionsAsHost
、それ以外の場合は にしたいと思いますfileTransferSessionsAsClient
。
私はこれについて鈍感な方法で行っていますか?コードを複製して、2 つの if ステートメントを作成する必要がありますか?
編集:
これは、より良い方法が見つからない場合、私が今しなければならないことです。見てみると、名前とディクショナリ項目の参照を除いて、コードはそれぞれ同じです。
public void UpdateFileTransferItems(FileTransferItem.FileTransferRole role)
{
if (role == FileTransferItem.FileTransferRole.Sender)
{
foreach (var hostSession in fileTransferSessionsAsHost)
{
var fileTransferItem = activeFileTransfers.FirstOrDefault(fti => fti.SessionId == hostSession.Key.SessionId);
if (fileTransferItem == null)
{
activeFileTransfers.Add(new FileTransferItem(hostSession.Key.FileName,
hostSession.Key.FileExtension,
hostSession.Key.FileLength,
FileTransferItem.FileTransferRole.Sender,
hostSession.Key.SessionId));
}
else
{
fileTransferItem.Update(hostSession.Value.TotalBytesSent,
hostSession.Value.TransferSpeed,
hostSession.Value.TotalBytesSent == hostSession.Key.FileLength);
}
}
}
else
{
foreach (var clientSession in fileTransferSessionsAsClient)
{
var fileTransferItem = activeFileTransfers.FirstOrDefault(fti => fti.SessionId == clientSession.Key.SessionId);
if (fileTransferItem == null)
{
activeFileTransfers.Add(new FileTransferItem(clientSession.Key.FileName,
clientSession.Key.FileExtension,
clientSession.Key.FileLength,
FileTransferItem.FileTransferRole.Sender,
clientSession.Key.SessionId));
}
else
{
fileTransferItem.Update(clientSession.Value.TotalBytesSent,
clientSession.Value.TransferSpeed,
clientSession.Value.TotalBytesSent == clientSession.Key.FileLength);
}
}
}
}