Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 被C类型转换搞糊涂了_C#_Type Conversion - Fatal编程技术网

C# 被C类型转换搞糊涂了

C# 被C类型转换搞糊涂了,c#,type-conversion,C#,Type Conversion,我不熟悉C,但熟悉vb.net 我的setVendor函数需要一个int和一个字符串 为什么这样做有效 shopify.setVendor(System.Convert.ToInt32(reader["ProductID"]), System.Convert.ToString(reader["Vendor"])); 但这两个参数都不适用: shopify.setVendor(int.Parse(reader["ProductID"]), reader["Vendor"].ToString);

我不熟悉C,但熟悉vb.net

我的setVendor函数需要一个int和一个字符串

为什么这样做有效

shopify.setVendor(System.Convert.ToInt32(reader["ProductID"]), System.Convert.ToString(reader["Vendor"]));
但这两个参数都不适用:

shopify.setVendor(int.Parse(reader["ProductID"]), reader["Vendor"].ToString);
非常困惑。它想要一个字符串,我给它一个字符串,但它不接受它。将字符串转换为int时出错

接受对象的Convert.ToInt32重载。int.Parse没有这样的重载。参数在编译时必须是字符串。您需要:

shopify.setVendor(int.Parse(reader["ProductID"].ToString()),
                  reader["Vendor"].ToString());
请注意第二个参数从ToString到ToString的更改。。。之前您指定了用于创建委托的ToString方法组;换成你打电话给ToString的零钱

或:

但是,理想情况下,您已经以正确的形式返回了值,因此您可以使用:

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


还要注意的是,setVendor不是一个传统的.NET方法名。

好吧,第一个问题

System.Convert.ToInt32。。。和System.Convert.ToString。。。将提供的参数分别转换为int和string,其格式与代码预期的格式相同

其次,它应该是ToString而不是ToString,因为您希望调用该方法:

reader["Vendor"].ToString()

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

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

这是一种安全的方法。

啊,我明白了,基本上是因为我错过了ToString arg!C需要很多时间来适应!干杯@麦克斯霍奇斯:不,那只是一个错误。另一个错误是,你调用int.Parsereader[ProductID],这将不起作用……给投票否决我的人。在我发布之前,我在这方面花了大量时间。除了ToInt32和int.Parse之外,我还尝试了intreader[ProductID]。我想你就是不能取悦一些人。我做VB已经20年了,但我决定用C编写我的第一个应用程序。我正在读一本C和VB.NET转换的书,但有时很难发现你的错误,特别是在一种新语言中。这并不是说我是一个悲观的投票者,但任何时候你说这失败了,你都应该给出准确的失败模式-包括异常或编译时错误。@JonSkeet我感谢你花时间和精力写答案,但我想我应该删除它,因为它被否决了,并且有两个电话要关闭它,对吗?你现在不能删除这个问题,因为它有一个向上投票的答案。不过,您仍然可以通过显示您在前面的代码中收到的错误消息来改进它,这甚至可能会让投票人改变主意。
reader["Vendor"].ToString()
int productId;
if(int.TryParse(reader["ProductID"].ToString(), out productId))
   shopify.setVendor(productId, reader["Vendor"].ToString());