List<T>.IndexOf
メソッドは、リスト内の指定されたオブジェクトを検索します。参照型の場合(およびAction<string>
が参照型の場合)、アイテムは参照等価によって比較されます。つまり、オブジェクト変数は実際に同じオブジェクトを参照する必要があります。あなたのケースでは
新しいAction<string>
オブジェクトは、あなたがIndexOf()
呼び出しが-1
を返す理由だ
(string i) =>
{
i = "First";
}
を指定するたびに作成されます。
最も簡単な修正はIndexOf()
コールに同じオブジェクトを渡すことです:
var firstAction = (string i) =>
{
i = "First";
};
myQ.Enqueue(firstAction);
// ...
int index = myQ.ToList().IndexOf(firstAction);
より柔軟なアプローチは、あなたが検索することができます上のプロパティとしてセッション名を持つ単純なクラスを定義することです:
public class QueueItem
{
public string SessionName { get; }
public Action<string> Action => i => i = SessionName;
public QueueItem(string sessionName)
{
SessionName = sessionName;
}
}
Queue<QueueItem> myQ = new Queue<QueueItem>();
myQ.Enqueue(new QueueItem("First"));
myQ.Enqueue(new QueueItem("Second"));
myQ.Enqueue(new QueueItem("Thrid"));
int index = myQ.ToList().FindIndex(x => x.SessionName == "First");
を
コードのもう1つの問題は、Action
を使用して文字列変数を割り当てる方法です。 str
の値が"One"
、ない"Two"
だろう、このコードの実行後
string str = "One";
Action<string> action = x => x = "Two";
action(str);
:このコードを考えてみましょう。アクションが呼び出されると、str
が値渡しされるため、アクション内のパラメータへの割り当て(または他のメソッド)は初期値に影響しません。詳細はquestionにチェックしてください。
あなたは修正することができ、その代わりにAction<string>
のFunc<string>
を持つと割り当てで返された値を使用して:
public class QueueItem
{
public string SessionName { get; }
public Func<string> Func =>() => SessionName;
public QueueItem(string sessionName)
{
SessionName = sessionName;
}
}
Queue<QueueItem> myQ = new Queue<QueueItem>();
myQ.Enqueue(new QueueItem("First"));
myQ.Enqueue(new QueueItem("Second"));
myQ.Enqueue(new QueueItem("Thrid"));
var queueList = myQ.ToList();
int index = queueList.FindIndex(x => x.SessionName == "First");
var result = queueList[index].Func();
あなたはなぜあなたはキューを使用している特定の位置でのアクションを見つける必要がある場合は? – InBetween
これは、私のニーズに最も適した方法です。アクションは、条件が満たされた特定の時間にのみ、即時に呼び出されないキューに積み重なります。 – TricksterJoe