Fsharp互动福

时间:2012-03-09 18:31:23

标签: reflection f# f#-interactive

我在fsharp interactive中有一个变量

val toto : obj = [["NKY INDEX"]]

(我通过调用普通的dotnet库获得了这个值,其原型告诉我它返回 obj

我想访问它里面的值,但我不确切知道它的类型。 所以我试着反思一下:

>toto.GetType();;
val it : Type =
  System.Object[,]
    {Assembly = mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;
     AssemblyQualifiedName = "System.Object[,], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
     Attributes = AutoLayout, AnsiClass, Class, Public, Sealed, Serializable;
     BaseType = System.Array;
     ContainsGenericParameters = false;
     CustomAttributes = seq [[System.SerializableAttribute()]];
     DeclaredConstructors = [|Void .ctor(Int32, Int32);
                              Void .ctor(Int32, Int32, Int32, Int32)|];
     DeclaredEvents = [||];
     DeclaredFields = [||];
     DeclaredMembers = [|Void Set(Int32, Int32, System.Object);
                         System.Object& Address(Int32, Int32);
                         System.Object Get(Int32, Int32);
                         Void .ctor(Int32, Int32);
                         Void .ctor(Int32, Int32, Int32, Int32)|];
     DeclaredMethods = [|Void Set(Int32, Int32, System.Object);
                         System.Object& Address(Int32, Int32);
                         System.Object Get(Int32, Int32)|];
     DeclaredNestedTypes = seq [];
     DeclaredProperties = [||];

它有一个Get方法,但是,当我尝试检索元素时,我收到错误。

>toto.Get(0,0);;

  toto.Get(0,0);;
  -----^^^

  error FS0039: The field, constructor or member 'Get' is not defined

检索内部元素的正确方法是什么?

PS:预先投射它会产生相同的

>(toto :?> System.Object[,]).Get(0,0);;

(toto :?> System.Object[,]).Get(0,0);;
----------------------------^^^

error FS0039: The field, constructor or member 'Get' is not defined

相同的。[0,0]

> toto.[0, 0];;

  toto.[0, 0];;
  ^^^^^^^^^^^

error FS0039: The field, constructor or member 'Item' is not defined

2 个答案:

答案 0 :(得分:2)

let toto = box (Array2D.init 1 1 (fun _ _ -> "NKY INDEX"))
(toto :?> string[,]).[0,0]

答案 1 :(得分:1)

我想象

let arr = toto :?> obj[,]  // downcast to actual type
let item = arr.[0,0]

是你想要的。

相关问题