代码之家  ›  专栏  ›  技术社区  ›  Wodzu

传递uknown参数问题的更好解决方案是什么?

  •  0
  • Wodzu  · 技术社区  · 15 年前

    我的问题是:

    ASP DetailsView DetailsViewInsertedEventArgs , DetailsViewDeletedEventArgs , DetailsViewUpdatedEventArgs

    以上所有事件都有共同的属性,我对其中两个很感兴趣: Exception ExceptionHandled

    我想创建一个这样的方法:

    public void DoSomething(ref CommonAncestorForDVArgs args)
    {
    
        if (args.Exception != null)
        {
            //do something with an exception
            args.ExceptionHandled = true;
        }
    }
    

    当然,这是不可能的,因为我已经在前面描述过了。

    public void DoSomething(Exception e, bool ExceptionHandled)
    {
    
        if (e.Exception != null)
        {
            //do something with an exception
            ExceptionHandled = true;
        }
    }
    

    但我想知道有没有更好的办法?

    3 回复  |  直到 15 年前
        1
  •  0
  •   Skizz    15 年前

    public void DoSomething (ref CommonAncestorForDVArgs args)
    {
      if (args.GetType () == typeof DetailsViewInsertedEventArgs || // syntax probably wrong here
          args.GetType () == some.other.type)
      {
        // do something with an exception
      }
    }
    

    在维护方面,这可能和我的另一个答案没有太大区别。

        2
  •  1
  •   Yogesh    15 年前

    interface 并得出 EventArgs 事件参数 您正在使用),例如:

    public interface ICommonAncestorForDVArgs
    {
        Exception Exception { get; set; }
        bool ExceptionHandled { get; set; }
    }
    

    然后在你的 DoSomething 方法:

    public void DoSomething(ref ICommonAncestorForDVArgs args)
    

    编辑: 另一种方法是反思。你可以为你的 方法如下(此代码不包括错误检查):

    public static void DoSomething<T>(ref T args)
    {
        Exception e = args.GetType().GetProperty("Exception").GetValue(args, null) as Exception;
    
        if (e != null)
        {
            //do something with an exception
    
            typeof(CommonAncestorForDVArgs).GetProperty("ExceptionHandled").SetValue(args, true, null);
        }
    }
    
        3
  •  0
  •   Skizz    15 年前

    public void DoSomething (ref DetailsViewInsertedEventArgs args)
    {
      DoCommonStuff (args);
      // do something with a DetailsViewInsertedEventArgs exception
    }
    
    public void DoSomething (ref DetailsViewDeletedEventArgs args)
    {
      DoCommonStuff (args);
      // something with a DetailsViewDeletedEventArgs exception
    }
    
    public void DoSomething (ref DetailsViewUpdatedEventArgs args)
    {
      DoCommonStuff (args);
      // do something with a DetailsViewUpdatedEventArgs exception
    }
    
    void DoCommonStuff (ref CommonAncestorForDVArgs args)
    {
      // common stuff
    }
    
    推荐文章