[英]how to read the values from the object variable in C#
我需要从object
类型的变量中读取值,例如,我有一个名为 result 的变量:
object result= h[key];
h[key]
是一个 hash 表,它向结果变量返回 5 个值。 如何在 SSIS package 中的 C# 脚本中将第一个值读取到字符串类型的局部变量?
我只能看到结果变量的GetType
、 Equals
、 ToString()
选项。
请问有什么帮助吗?
有样本:
有样品; 公共无效 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.