C# 中 (int) 和 Convert.toint32 之间的区别

发布于 2024-09-06 10:58:46 字数 296 浏览 3 评论 0原文

当我将一个对象转换为 int

(int)object

时,当对象值为 0 时,他会给我错误,指出特定的强制转换无效。

当我将一个对象转换为 int 时,

convert.toint32(object)

他会工作并给我 0 意味着强制转换是有效的。

我想知道两者之间有什么区别。

1. (int)object
2.convert.toint32(object)

when i convert a object to int by

(int)object

then when the object value is 0 then he give me error that specific cast not valid.

when i convert a object to int by

convert.toint32(object)

then he works and give me 0 means cast is valid.

and i want to know that what is difference between both.

1. (int)object
2.convert.toint32(object)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

迷你仙 2024-09-13 10:58:46

(int) 仅当对象实际上 整数时才有效。例如,(int) "12" 会给您一个无效的强制转换异常。

Convert.ToInt32 尝试最好将您提供的任何内容转换为整数。因此 Convert.ToInt32("12") 将返回 12。准确地说,如果对象实现 IConvertible (System.String 执行此操作),然后 Convert.ToInt32 将调用 IConvertible.ToInt32 方法。

(int) works only if the object actually is an integer. For example, (int) "12" will give you an invalid cast exception.

Convert.ToInt32 tries it's best to convert whatever you give it into an integer. So Convert.ToInt32("12") will return 12. To be precise, if the object implements IConvertible (which System.String does), then Convert.ToInt32 will call the IConvertible.ToInt32 method.

泪冰清 2024-09-13 10:58:46

两种方法完全不同。第一个是转换,第二个是转换

非整数值需要转换为int时,使用转换

转换用于在实例已经是 int 类型时将实例拆箱返回到 int 装箱为 Object 类型。

Both methods are completely different. First one is casting and the second one is conversion.

Conversion is used when a non-integer value requires to be converted into int.

Casting is used to unbox the instance back to int when the instance is already a type of int boxed into Object type.

香橙ぽ 2024-09-13 10:58:46

一般意义上,(Type)val 可以表示:

  • 由语言定义的内置转换(例如,float 和 int 之间)
    • 这可能需要实际操作(float <==> int 就是一个很好的例子)
    • 或者可能只是为了编译器的利益(例如 int <===> an-int-enum)
  • 引用强制转换(它永远不会更改引用或对象;它只是键入其本地句柄)
    • 可能需要类型检查(例如,object ===> IDataReader)
    • 但可能已经知道是真的(例如,IDataReader ===> 对象)
  • 装箱/拆箱操作(始终初始化一个值类型,或者在堆上创建一个新对象[除了空装箱 Nullable]
  • 类型定义的转换运算符(隐式或显式),它运行任何代码在类型中定义

给定一个 object 值,(int)object 将假定它是一个拆箱操作,因此仅当对象一个装箱的int(或一个装箱的int-enum),如果对象值实际上是一个字符串或一个装箱的float,它将失败。 Convert.ToInt32 的工作方式

不同;它运行许多测试,尝试将诸如从浮点类型转换(上面介绍的)和解析字符串(映射到 >int.Parse)。

In the general sense, (Type)val can represent:

  • an inbuilt conversion (for example, between a float an an int), defined by the language
    • which might require an actual operation (float <===> int being a good example)
    • or might just be for the beefit of the compiler (int <===> an-int-enum, for example)
  • a reference cast (which never changes the reference or the object; it just types the local handle to it)
    • which might require a type check (for example, object ===> IDataReader)
    • but might be already known to be true (for example, IDataReader ===> object)
  • a boxing / unboxing operation (which always initializes a value-type, or creates a new object on the heap [except for null-boxing a Nullable<T>]
  • a type-defined conversion operator (implicit or explicit), which runs whatever code is defined in the type

Given an object value, the (int)object will assume it is an unboxing operation, so will only work if the object is a boxed int (or a boxed int-enum). It will fail if the object value is actually a string or a boxed-float etc.

Convert.ToInt32 works differently; it runs a number of tests, to attempt to bring together things like casting-from-a-float (covered above) and parsing a string (which maps to int.Parse).

任谁 2024-09-13 10:58:46

有很多方法可以转换为 int,很大程度上取决于您的来源。

最需要记住的是错误检查,没有一种方法本身是万无一失的,因此您需要决定如何处理它们。

使用 (int) 进行转换、使用 Convert.ToInt32() 进行转换、使用 int.Parse() 进行解析都可能会生成 InvalidCastException、FormatException 和 OverflowException 等异常,并且应该使用 try/catch 来处理失败的结果。

如果解析成功,则使用 int.TryParse() 进行解析将返回 true/false 结果,如果成功,则将该值设置为函数调用中给定的 out 参数。

如果您确实尝试获取任何对象并将其转换为 int,那么您可能最好使用 Convert.ToInt32,例如:

public void TestFunction(object input)
  try {
    int value = Convert.ToInt32(input);
    SomeOtherFunction(value);
  }
  catch (Exception ex) {
    Console.WriteLine("Could not determine integer value");
  }
}

另一种可能性是依赖于在 .ToString() 中生成可用值的对象,例如:

public void TestFunction(object input)
  try {
    int value = int.Parse(input.ToString());
    SomeOtherFunction(value);
  }
  catch (Exception ex) {
    Console.WriteLine("Could not determine integer value");
  }
}

There are many ways to convert to an int, a lot depends on what your source is.

The biggest thing to keep in mind is error checking, none of the methods are fool proof on their own and so you need to decide how you want to approach them.

Casting with (int), Converting with Convert.ToInt32(), Parsing with int.Parse() all can generate exceptions such as InvalidCastException, FormatException and OverflowException and should use try/catch to handle failed result.

Parsing with int.TryParse() will return a true/false result of if the parsing was successful and if successful set the value to the out parameter given in the function call.

If you are truly trying to take any object and turn it into an int, you are probably best with Convert.ToInt32 such as:

public void TestFunction(object input)
  try {
    int value = Convert.ToInt32(input);
    SomeOtherFunction(value);
  }
  catch (Exception ex) {
    Console.WriteLine("Could not determine integer value");
  }
}

Another possibility would be relying on the object producing a usable value in .ToString() such as:

public void TestFunction(object input)
  try {
    int value = int.Parse(input.ToString());
    SomeOtherFunction(value);
  }
  catch (Exception ex) {
    Console.WriteLine("Could not determine integer value");
  }
}
无妨# 2024-09-13 10:58:46

(int) Something 可以在两种情况下工作:

  1. something 一个被装箱到对象中的 int,我们使用取消装箱的调用。如果将 int 放入 ArrayList 或 HttpSession 等中,就会发生这种情况...

  2. 某物 不是 int,但它的类型可以是显式转换为 int,例如内置类型的短整型、长整型、浮点型,或实现显式强制转换运算符的类型。

另一方面,Convert.ToInt32 只是调用 something 的类型 IConvertible.ToInt32 方法,它或多或少相当于 int.Parse(something)

There are two scenarios where (int) something works:

  1. The something is an int that was boxed into an object, and we use the call to unbox it. This is what happens if you put the int into an ArrayList, or in HttpSession, etc...

  2. The something is not an int, but it's type can be explicitly converted into an int, for example, short, long, float of the build-in types, or a type that implemented the explicit cast operator.

Convert.ToInt32, on the other hand, simply calls something's type IConvertible.ToInt32 method, and it's more or less equivalent to int.Parse(something)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文