简体   繁体   English

与C#类型转换混淆

[英]confused by C# type conversion

I'm new to C# but familiar with vb.net 我是C#的新手,但熟悉vb.net

my setVendor functions expects an int and a string 我的setVendor函数需要一个int和一个字符串

why does this work 为什么这项工作

shopify.setVendor(System.Convert.ToInt32(reader["ProductID"]), System.Convert.ToString(reader["Vendor"]));

but this fails for both parameters: 但这对两个参数都失败:

shopify.setVendor(int.Parse(reader["ProductID"]), reader["Vendor"].ToString);

very confused. 很迷茫。 It wants a string and I give it a string but it doesn't accept it . 它需要一个字符串,我给它一个字符串,但是它不接受。 . . error converting string to int 将字符串转换为int时出错

There's an overload of Convert.ToInt32 which accepts object . 接受objectConvert.ToInt32有一个重载。 There's no such overload for int.Parse . int.Parse没有这样的重载。 The argument must be a string at compile time . 参数在编译时必须是string You would need: 您将需要:

shopify.setVendor(int.Parse(reader["ProductID"].ToString()),
                  reader["Vendor"].ToString());

(Note the change from ToString to ToString() for the second argument... previously you were specifying the ToString method group which is used to create delegates; with the change you're calling ToString instead.) (请注意,第二个参数从ToString更改为ToString() ...之前,您指定了用于创建委托的ToString方法组;使用此更改,您正在调用 ToString 。)

Or: 要么:

// This only works if the value *is* a string
shopify.setVendor(int.Parse((string) reader["ProductID"]),
                  reader["Vendor"].ToString());

Ideally, however, you'd get back the values in the correct forms already, so you could use: 但是,理想情况下,您已经可以正确的形式获取值,因此可以使用:

shopify.setVendor((int) reader["ProductID"], (string) reader["Vendor"]);

Or: 要么:

// Set up productIdColumn and vendorColumn first
shopify.setVendor(reader.GetInt32(productIdColumn), reader.GetString(vendorColumn));

Also note that setVendor is not a conventional .NET method name. 还要注意, setVendor不是常规的.NET方法名称。

Well, for your first question 好吧,第一个问题

System.Convert.ToInt32(...) and System.Convert.ToString(...) convert the supplied arguments to int and string respectively which is in the correct format as expected by your code. System.Convert.ToInt32(...)System.Convert.ToString(...)将提供的参数分别转换为intstring ,它们的格式与您的代码所期望的正确格式相同。

Secondly, it should be ToString() not ToString since you want to make a call to the method: 其次,它应该是ToString()而不是ToString因为您要调用该方法:

reader["Vendor"].ToString()

第二个代码段中的ToString部分需要括号(),因为它是方法,而不是成员或属性。

int productId;
if(int.TryParse(reader["ProductID"].ToString(), out productId))
   shopify.setVendor(productId, reader["Vendor"].ToString());

Would be a safe way to do it. 将是一种安全的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM