2017-04-12 141 views
-4

我试图用它的所有函数构建一个类。如何在while循环中获得结果以便将它用作函数中的返回值,c#

我的函数试图返回我的变量结果,这是一个TimeSpan类型。但是我无法将dataRecupere从条件中解脱出来,以便将其用于我的结果。

这里是我的代码:

public TimeSpan differenceDate(string idAdmission) 
     { 
      TimeSpan resultat; 
      TimeSpan dateRecupere; 
      string requete = "SELECT AdmitDate FROM AdmissionRecords WHERE AdmissionID = @idAdmission"; 
      connexion.Open(); 

      SqlCommand commande = new SqlCommand(requete, connexion); 
      commande.Parameters.AddWithValue("@idAdmission", idAdmission); 
      SqlDataReader lecteur = commande.ExecuteReader(); 
      if (lecteur.HasRows) 
      { 
       lecteur.Read(); 
       dateRecupere = TimeSpan.Parse((lecteur["AdmitDate"]).ToString()); 

      }    
      connexion.Close(); 
      return resultat = dateRecupere - DateTime.Now.TimeOfDay; 
     } 
+1

只要改变'回报resultat = ...''要返回dateRecupere - DateTime.Now.TimeOfDay' – pstrjds

+0

我试了一下。我的控制台正在返回一个错误,说我的语言环境变量没有从resultat或dateRecupere分配! –

+1

你得到了什么确切的错误信息?不相关,但查找'using'关键字。如果在代码中引发异常,那么您现在将打开数据库连接。 –

回答

0

你的问题是,你正在分配的结果,而不是返回它。我还将清理代码并添加一些调用Dispose,因为您使用的对象实现了IDisposable。关于未赋值的变量,C#设计中推荐的一件事是在您需要它们之前不要声明变量。在C中,你必须在方法的顶部声明变量,但在C#中你不需要。只需在需要时声明它们。

public TimeSpan differenceDate(string idAdmission) 
{ 
    // Declaring as a constant 
    const string ReQuete = "SELECT AdmitDate FROM AdmissionRecords WHERE AdmissionID = @idAdmission"; 

    SqlCommand commande = null; 
    try 
    { 
     connexion.Open(); 
     commande = new SqlCommand(ReQuete, connexion); 

     // I am making the assumption that the AdmitDate is a Date field, 
     // if it is a string, then just change this to string and check 
     // for null before parsing it. Note also that I am using the 
     // ExecuteScalar method since you are running a scalar query. 
     // This way you don't have to create a reader and have the 
     // additional cleanup code associated with a reader 
     DateTime? result = (DateTime?)commande.ExecuteScalar(); 
     if (result.HasValue) 
     { 
      return result.Value - DateTime.Now.TimeOfDay; 
     } 
     else 
     { 
      return TimeSpan.Zero; // I think this is probably what you would want as the default return value if there is no date 
     } 
    } 
    finally 
    { 
     // If an object implements IDisposable, you should call Dispose 
     // or place it in a using statement 
     commande?.Dispose(); // Newer C# syntax, old was if (commande != null) 
     // we should be sure the connection is open before closing it 
     if (connexion.State == Connection.Open) connexion.Close(); 
    } 
} 
相关问题