如何从静态函数返回类对象 [英] How do I get class objects back from a static function

查看:163
本文介绍了如何从静态函数返回类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何处理从具有许多返回变量的静态函数返回的类对象。您不能对对象使用foreach语句。如何从静态函数中获取类对象?



Default.aspx.cs

 < span class =code-keyword> protected   void  Button1_Click( object  sender,EventArgs e )
{
ID = TextBox1.Text;
object returnedData = Getdata(ID);
????

}
public static 对象 Getdata(字符串 ID)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
List< dataclass> returndata = new List< dataclass>();
dataclass dc = new dataclass();
string connStr = ConfigurationManager.ConnectionStrings [ 的JSONObject]的ConnectionString。
string cmdStr = SELECT([idd] ],[datetime],[col1],[col2],[col3])FROM [jsondata] WHERE [idd] = @ idd;;
尝试
{
使用(SqlConnection conn = new SqlConnection(connStr))
{
使用(SqlCommand cmd = new SqlCommand(cmdStr,conn))
{
conn.Open();
cmd.Parameters.AddWithValue( @ idd,ID);
SqlDataReader myReader = cmd.ExecuteReader();
if (myReader.Read())
{
dc.idd = Convert.ToString(myReader [ idd]);
dc.datetime = Convert.ToString(myReader [ datetime]);
dc.col1 = Convert.ToString(myReader [ col1]);
dc.col2 = Convert.ToString(myReader [ col2]);
dc.col3 = Convert.ToString(myReader [ col3]);
returndata.Add(dc);
}
}
}
}
catch (例外情况)
{

}
return returndata.ToArray();
}< small> < / small >



Class1.cs

  public   class  dataclass 
{
public string idd { get ; set ; }
public string datetime { get ; set ; }
public string col1 { get ; set ; }
public string col2 { get ; set ; }
public string col3 { get ; set ; }
}

解决方案

首先,使用松散打字是犯罪行为使用基于严格打字的系统。此方法的签名必须是

  static  datatype [] Getdata(字符串 ID); 



从这种方法的主体可以看出这一点。



现在,在几乎所有情况下,使用

catch(Exception ex){}

在这种特殊情况下,您不应该在此方法中处理异常。通常,仅在本地处理异常确实是一件坏事。在大量代码中,您应该允许异常向上传播到最终捕获它的某个点。在每个线程中应该处理异常的点很少,但每个线程最终应该在某处捕获每个异常。我把这些点称为能力点,它们应该写在你确切知道如何处理某些(不是全部)异常类型的地方。



关于静态方法的问题根本没有意义。创建某个对象后,创建它的方法无关紧要。你了解静态和实例(非静态)方法是什么?可能不是。 Instance方法有一个隐含参数this,用于访问类实例。如果不清楚,请阅读我过去的答案:

在c#中输入类型 [ ^ ],

什么使静态可访问的方法? [ ^ ],

C#windows基于这个关键词及其在应用程序中的用途 [ ^ ]。



-SA

I am not sure how to handle a class object returning from a static function with many returning variables. You can not use a "foreach" statement with an object. How do I get class objects back from a static function?

Default.aspx.cs

protected void Button1_Click(object sender, EventArgs e)
{
    ID = TextBox1.Text;
    object returnedData = Getdata(ID);
    ????

}
public static object Getdata(string ID)
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    List<dataclass> returndata = new List<dataclass>();
    dataclass dc = new dataclass();
    string connStr = ConfigurationManager.ConnectionStrings["jsonobject"].ConnectionString;
    string cmdStr = "SELECT ([idd],[datetime],[col1],[col2],[col3]) FROM [jsondata] WHERE [idd]=@idd;";
    try
    {
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@idd", ID);
                SqlDataReader myReader = cmd.ExecuteReader();
                if (myReader.Read())
                {
                    dc.idd = Convert.ToString(myReader["idd"]);
                    dc.datetime = Convert.ToString(myReader["datetime"]);
                    dc.col1 = Convert.ToString(myReader["col1"]);
                    dc.col2 = Convert.ToString(myReader["col2"]);
                    dc.col3 = Convert.ToString(myReader["col3"]);
                    returndata.Add(dc);
                }
            }
        }
    }
    catch (Exception ex)
    {

    }
    return returndata.ToArray();
}<small></small>


Class1.cs

public class dataclass
{
    public string idd { get; set; }
    public string datetime { get; set; }
    public string col1 { get; set; }
    public string col2 { get; set; }
    public string col3 { get; set; }
}

解决方案

First of all, it's a crime to use loose typing with the systems based on strict typing. The signature of this method must be

static datatype[] Getdata(string ID);


This is apparent from the body of this method.

Now, in almost all cases, it's a crime to block exception propagation using
catch (Exception ex) {}.
In this particular case, you should not handle exception in this method. Generally, just handling exceptions locally is really a bad thing. In major mass of code, you should allow the exception to propagate up the stack to some point where it is ultimately caught. There should be very few points where exceptions are handled, in each thread, but each and every thread should eventually catch each and every exception somewhere. I call those point "competency points", they should be written where you know exactly what to do with certain (not all) exception types.

The question about static method simply makes no sense. Once some object is created, it does not matter on what method it was created. Do you understand what static and instance (non-static) methods are? Probably not. Instance method has one implicit parameter, "this", for access to the class instance. If this is not clear, please read my past answers:
Type casting in c#[^],
What makes static methods accessible?[^],
C# windows base this key word related and its uses in the application[^].

—SA


这篇关于如何从静态函数返回类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆