如何从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 [主题]; ///从哈希表
}
答
假如你知道结果的类型,就可以把对象var result = (MyType) h[key]
编辑:使用您的函数中得到第一价值var result = ((LocationInfo) h[key]).A
答
更新: 玉以及你有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];
变化(对象)到(LocationInfo),然后制作一些属性来获取值。 – cush 2011-04-28 14:48:59
是的,我非常感谢 – lch 2011-04-28 15:03:40