4

ConvertクラスとインターフェイスIConvertibleDataRow. このコードがある場合:

string s="25";
int x= Convert.ToInt32(s);

への呼び出しConvert.ToInt32(s)は、次を実行します。

((IConvertible)s).ToInt32()

では、これは次のようなコード行でどのように機能しますか:

Convert.ToInt32(myDataRow["intField"]);

DataRow もオブジェクトも IConvertible を実装していない場合は?

4

1 に答える 1

8

The DataRow fields are exposed as objects, so the call is made to Convert.ToInt32(object value), which does exactly what you said in your question:

return value == null? 0: ((IConvertible)value).ToInt32(null);

The runtime attempts to perform a conversion from object to IConvertible. It doesn't matter that object doesn't implement the interface; what matters is that whatever actual, concrete type is in the DataRow at runtime has to implement the interface. All of the built-in CLR base types implement IConvertible, for example, so it will call String.ToInt32() or Boolean.ToInt32() or whatever. The interfaces are implemented explicitly, so you can't call those methods directly on your own string or bool, but you could upcast to IConvertible and do it.

object s = new System.String('1', 3);
var i = Convert.ToInt32(s);

// s = "111"; i = 111

If you try to run that method on an object that doesn't implement IConvertible, you'll get a runtime typecast exception:

var o = new object();
var x2 = Convert.ToInt32(o);

// throws System.InvalidCastException: "Unable to cast object of type 'System.Object' to type 'System.IConvertible'."
于 2012-01-30T14:24:04.543 に答える