나는 List<Action<int>>
을 생성하고 나중에이 클래스를 보유하는 클래스가 있습니다. 이 클래스는이 목록에서 대리인을 추가 및 제거 할 수 있습니다. 이것은 사람들이 너무 공상에 빠지지 않는 한 잘 작동합니다. 제거 할 수없는 익명 함수를 처리하기 위해 위임 대상이 null 인 지 확인합니다. null 인 경우 예외가 발생합니다. 이 문제는 함수가 포함 된 익명의 대리자가있을 때 발생합니다. 이것은 목표를 가지고 있지만 마찬가지로 제거 할 수 없습니다. 단순화 된 코드는 아래 내가익명 함수를 식별하는 방법
p => { fake.Test(p); counter++; }
누군가가 그것을 시도하는 경우 내가 던질 수있는 익명 함수입니다 식별 할 수있는 방법이 필요합니다 내 문제
public class MyDelegateContainer
{
List<Action<int>> m_Container = new List<Action<int>>();
public void Add(Action<int> del)
{
if (del.Target == null)
{
throw new Exception("No static handlers");
}
m_Container.Add(del);
}
public bool Remove(Action<int> del)
{
if (m_Container.Contains(del))
{
m_Container.Remove(del);
return true;
}
return false;
}
}
public class MyFakeActionClass
{
public void Test(int temp) { }
}
class Program
{
static void Main(string[] args)
{
bool removed = false;
int counter = 0;
MyDelegateContainer container = new MyDelegateContainer();
MyFakeActionClass fake = new MyFakeActionClass();
//container.Add(p => { }); //Throws, this is what I want to happen
container.Add(fake.Test); //Works, this is the use case
removed = container.Remove(fake.Test); //Works, this is the use case
Debug.Assert(removed);
container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
Debug.Assert(removed);
}
}
보여줍니다. 어떤 도움 주셔서 감사합니다
편집 : 익명 함수에 대해 변수 Action<int>
을 사용할 수 있으며 모든 것이 작동하지만 추가 및 제거가 결코 실제로 같은 범위에 있지 않음에 유의해야합니다.
식별되면 익명으로 처리되지 않습니다. 대신에 클로저를 찾으십니까? –
익명의 기능을 감지하는 방법이 필요합니다 – Steve
@Steve - 83 개의 답변 중 28 개가 답답합니다! O_O 그리고 나는 단지 당신이 좋은 점수를 가지고 있다고 말하고 있습니다.) – BeemerGuy