如何从C#中的对象变量

问题描述:

我需要从一个变量是object类型的用于e..g ..读取的值读取的值,我有一个变量被称为结果为:如何从C#中的对象变量

object result= h[key]; 

h[key]是一个散列表,它返回5个值给结果变量。如何在SSIS包中的C#脚本中将第一个值读取到我的局部变量类型字符串中?

我只能看到GetType,Equals,ToString()结果变量的选项。

请帮忙吗?

有样品:

有样品; public void SQLLoop() { string bp,ap,ep,s,vs; LocationInfo info = new LocationInfo(); string connection =“Server = Sname; Database = Dname; Integrated Security = 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; 
    } 


} 

现在

公共无效FUN1() { VAR结果=(对象)H [主题]; ///从哈希表

}

+0

变化(对象)到(LocationInfo),然后制作一些属性来获取值。 – cush 2011-04-28 14:48:59

+0

是的,我非常感谢 – lch 2011-04-28 15:03:40

假如你知道结果的类型,就可以把对象var result = (MyType) h[key]

编辑:使用您的函数中得到第一价值var result = ((LocationInfo) h[key]).A

+0

该类型除了也是一个对象类型,哈希表返回的值也是一个对象现在我该如何读取这些对象的值。对于e..g。,哈希的返回值是“Stack”“overflow”两个值,那么如何将这些值读入我的局部变量 – lch 2011-04-28 14:28:33

+0

如果您返回“Stack”“overflow”,那么您可以执行var'result = ((List )h [key])。First()'或类似的IEnumerable – tchrikch 2011-04-28 14:30:52

+0

我添加了样本,我想要基本达到 – lch 2011-04-28 14:45:12

你要投结果你期待的类或接口读取值。

var result = (IExpectedObject)h[key]; 
+0

我收到错误IExpectedObject没有程序集或目录 – lch 2011-04-28 14:22:37

+0

类型或名称空间找不到 – lch 2011-04-28 14:22:52

+0

IExcpectedObject只是一个例子。你必须在你的代码中放入你期望结果的ACTUAL类型。 – 2011-04-28 14:23:32

更新: 玉以及你有LocationInfo class所以做这样的事情:

LocationInfo result = (LocationInfo)h[key]; 

然后只是在L用于检索字符串的ocationInfo类。

您可能需要投射哈希表中的对象。因此,像:

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]; 
+0

该类型是除了也是一个对象类型,哈希表返回的值也是一个对象现在我怎么读取这些对象的值。对于e..g。,散列的返回值是“堆栈”“溢出”两个值,那么我如何将这些值读入我的局部变量 – lch 2011-04-28 14:27:42

+0

您是否有更多我们可以查看的代码?就像你如何加入散列表一样?当你添加到这个散列表中时,我需要看看你在做什么。 – cush 2011-04-28 14:31:56

+0

我添加了样本,我想基本达到 – lch 2011-04-28 14:46:15