在C#中给出事件参数

时间:2014-12-17 10:27:28

标签: c# events out

我想在事件上给出一个out参数,但它不起作用

像这样

错误:无法在anonyme方法或lambda表达式中使用参数输出

public void CallMyMethod()
{
  //{...  code here`removed...just for initialize object}

  int? count = null;
  MyMethod(myObject,count);
}
public static void MyMethod(AnObject myObject,out int?count)
{
    //{... code removed...}
    IEnumerable<AnAnotherObject> objects = myObject.GetAllObjects();//... get objects
    count = (count == null) ? objects.Count() : count;
    MyPopup popup = CreateMypopup();
    popup.Show();
    popup.OnPopupClosed += (o, e) =>//RoutedEventHandler
    {
        if (--count <= 0)
        {
            Finished();//method to finish the reccursive method;
        }
        else
        {
            MyMethod(myObject, out count);
        }
    };
}

1 个答案:

答案 0 :(得分:0)

将参数传递给事件处理程序的标准方法是定义自己的类

public class MyObjectArgs: EventArgs
{
    MyObject myObj {get;set}
    int? Count {get; set;}
}

然后将这个类的同一个实例传递给递归调用

public void CallMyMethod()
{
  //{...  code here`removed...just for initialize object}
  MyObjectArgs args = new MyObjectArgs();
  args.Count = null;
  args.myOby = myObject;
  MyMethod(args);
}

public static void MyMethod(MyObjectArgs args)
{
    //{... code removed...}
    IEnumerable<AnAnotherObject> objects = args.myObj.GetAllObjects();//... get objects
    args.Count = (args.Count == null) ? objects.Count() : args.Count;
    MyPopup popup = CreateMypopup();
    popup.Show();
    popup.OnPopupClosed += (o, e) =>//RoutedEventHandler
    {
        if (--args.Count <= 0)
        {
            Finished();//method to finish the reccursive method;
        }
        else
        {
            MyMethod(args);
        }
    };
}

您计算对象的行似乎也不正确,也许您想要这个?

args.Count = (args.Count == null) ? objects.Count() : args.Count + objects.Count();