2009-08-04 51 views
0

我有一个CustomerRepository类(在我的BL),和我返回集合如下:定制收集问题

public static ICollection<Customer> FindCustomers() 
    { 
     Collection<Customer> customers = null; 
     try 
     { 
      customers = DAL.GetCustomers();    
     } 
     catch (Exception ex) 
     { 
      //log and re-throw exception here 
     } 
     return customers; 
    } 

我有这几个问题:

  1. 是try/catch块好吗?
  2. 我在外面尝试创建集合,并将其返回外部。

我可以忽略这里的任何最佳实践吗?

很想知道这里潜在的陷阱:)

+0

只是一个评论,为什么ICollection而不是IQueryable。顺便说一句,在TRY – StevenMcD 2009-08-04 08:52:47

回答

3

这是罚款(地道)

public static ICollection<Customer> FindCustomers() 
{ 
    try 
    { 
     return DAL.GetCustomers();   
    } 
    catch (Exception ex) 
    { 
     //log and re-throw exception here 
    } 
} 

我想补充一点,返回的IQueryable(或者,如果不可行的IEnumerable)可能是一个更好的主意以便将来您班级的数据安排将有更多空间。

+0

+ IQueryable/IEnumerable + – 2009-08-04 09:00:43

3
public static ICollection<Customer> FindCustomers() 
{ 
     try 
     { 
      return DAL.GetCustomers(); 
     } 
     catch (Exception ex) 
     { 
      //log here 
      throw; 
     } 
} 

我觉得这是更好的版本

0

如果假设一个错误出现在try块之前return语句,如下面的代码我正在手动抛出一个异常,并在编译器警告我会发生什么return h;这行代码是无法访问的。

public int Test() 
     { 
      try 
      { 
       int h = 0; 
       h = 100; 
       throw new Exception(); 
       return h; 
      } 
      catch (Exception ex) 
      { 
       throw; 
      } 
     } 

可以有这样的警告吗?

+0

+1内有太多的大括号最好的做法是让int h;在try外面,h = 0里面try和return h;在尝试之外。如果你能照顾它,你为什么要忽略这个警告? – 2009-08-04 09:51:56

0

如果你在try里面做了一些处理,然后在外面声明你的返回对象,然后将它们返回到catch之外。所以我认为你写的是正确的。

我想如果您使用更多特定的接口(如IEnumerable <>),那么您的使用者(或上层/层)可能在使用您的集合类时遇到问题。他们可能需要添加更多的工作(如IEnumerable不支持Count属性)。使用ICollection> <>或甚至收集<>也应该没问题。