简体   繁体   中英

confused by C# type conversion

I'm new to C# but familiar with vb.net

my setVendor functions expects an int and a string

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

There's an overload of Convert.ToInt32 which accepts object . There's no such overload for int.Parse . The argument must be a string at compile time . 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.)

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.

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.

Secondly, it should be ToString() not ToString since you want to make a call to the method:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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