簡體   English   中英

如何從 C# 中的 object 變量中讀取值

[英]how to read the values from the object variable in C#

我需要從object類型的變量中讀取值,例如,我有一個名為 result 的變量:

object result= h[key];

h[key]是一個 hash 表,它向結果變量返回 5 個值。 如何在 SSIS package 中的 C# 腳本中將第一個值讀取到字符串類型的局部變量?

我只能看到結果變量的GetTypeEqualsToString()選項。

請問有什么幫助嗎?

有樣本:

有樣品; 公共無效 SQLLoop() { 字符串 bp,ap,ep,s,vs; 位置信息信息 = 新位置信息(); 字符串連接=“服務器=Sname;數據庫=Dname;集成安全=SSPI”; SqlConnection conn = new SqlConnection(connection);

    conn.Open();

   SqlCommand sqlcmd = new SqlCommand("SELECT Bp,Ap,EP,SL,VSr from Table1", conn);
   SqlDataReader rs=sqlcmd.ExecuteReader();


        while (rs.Read())
        {
            bp = rs.GetValue(0).ToString();
            ap = rs.GetValue(1).ToString();
            ep = rs.GetValue(2).ToString();
            s = rs.GetValue(3).ToString();
            vs = rs.GetValue(4).ToString();
            info.loadLocationInfo(ap, bp, ep, s, vs);
            h.Add(s, info);

        }
        conn.Close();

    }

public class LocationInfo
{
    String A;
    String B;
    String E;
    String S;
    String V;
    int id;

    public LocationInfo()
    {
    }

    public void loadLocationInfo(String a,String b,String e,String s,String v)
    {
        A =a ;
        B  =b ;
        E=e ;
       S =s;
        V = v;
    }


}

現在

public void fun1() { var result = (object )h[subject]; ///從hash表中讀取值

}

您必須將結果轉換為您期望的 class 或接口。

var result = (IExpectedObject)h[key];

假設您知道結果的類型,您可以轉換 object var result = (MyType) h[key]

編輯:在你的 function 中使用它來獲得第一個值var result = ((LocationInfo) h[key]).A

更新:好吧,你有 LocationInfo class 所以做這樣的事情:

LocationInfo result = (LocationInfo)h[key]; 

然后只需在 LocationInfo class 上創建一些屬性即可檢索您的字符串。

您可能需要轉換哈希表中的 object。 所以像:

result = (Type)h[key];

這是它如何工作的示例:

Person1 = new Person("David", "Burris");
Person2 = new Person("Johnny", "Carrol");
Person3 = new Person("Ji", "Jihuang");

//The Add method takes Key as the first parameter and Value as the second parameter.

try
{
    MyTable.Add(Person1.Lname, Person1);
    MyTable.Add(Person2.Lname, Person2);
    MyTable.Add(Person3.Lname, Person3);

}
catch (ArgumentException ae)
{
    MessageBox.Show("Duplicate Key");
    MessageBox.Show(ae.Message);
}

因此,當您想從表中檢索時,您將執行以下操作:

Person result = (Person)h[key];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM