在Python中获取C# Int64对象异常:返回Python int类型问题
Great question! This behavior comes down to how .NET/Python interop frameworks (like Python.NET or IronPython) handle type marshaling between C# and Python types. Let me break this down for you:
Why Int64 gets converted to Python int
C#'s System.Int64 is a 64-bit signed integer type, and Python's built-in int can represent arbitrary-precision integers—meaning it can fully cover the range of Int64 values. To make interop feel more natural for Python developers, the interop framework automatically marshals Int64 values to Python's native int by default.
In contrast, System.DateTime has no direct equivalent in Python's standard library (Python's datetime.datetime is similar but not identical in implementation), so the framework leaves it as a System.DateTime instance instead of converting it.
How to strictly keep the System.Int64 type
If you need to retain the actual System.Int64 object (critical for your external program integration), here are a few reliable solutions:
1. Use the Int64 constructor directly
Instead of using Int64.Parse() (which returns an Int64 that gets marshaled to Python int), create the Int64 instance directly using its constructor. For string inputs, first parse to a Python int, then pass it to the Int64 constructor:
from System import Int64 # For direct numeric values l = Int64(123) print(l, type(l)) # Output: 123 <class 'System.Int64'> # For string inputs str_value = '456' l = Int64(int(str_value)) print(l, type(l)) # Output: 456 <class 'System.Int64'>
2. Use TryParse with an out parameter
If you want to handle parsing validation (like checking if the string is a valid integer), use Int64.TryParse() with an out parameter. This bypasses the automatic marshaling because you're directly accessing the Int64 value from the out result:
from System import Int64, Nullable str_value = '789' result = Nullable[Int64]() is_valid = Int64.TryParse(str_value, result) if is_valid: l = result.Value print(l, type(l)) # Output: 789 <class 'System.Int64'> else: print("Invalid integer string")
3. Disable automatic type marshaling (Python.NET specific)
If you're using Python.NET, you can configure the runtime to disable automatic conversion of value types. Add this at the start of your script:
import clr clr.SetClrType(True) # Forces .NET types to remain as their original CLR types from System import Int64 l = Int64.Parse('123') print(l, type(l)) # Output: 123 <class 'System.Int64'>
Note that this will affect all value types (like Int32, Double, etc.), so keep that in mind if you rely on native Python types elsewhere.
Verification
To confirm you have a genuine System.Int64 instance, you can also check using isinstance:
print(isinstance(l, Int64)) # Should return True if it's the correct type
内容的提问来源于stack exchange,提问作者Josef Kvita

