【问题标题】:Error creating instance of C# class in F# script file在 F# 脚本文件中创建 C# 类的实例时出错
【发布时间】:2023-11-30 03:39:02
【问题描述】:

我想在 F# 中使用以下 C# 类

using System;
using System.Collections.Generic;
using System.Text;

namespace DataWrangler.Structures
{
    public enum Type { Trade = 0, Ask = 1, Bid = 2 }

    public class TickData
    {
        public string Security = String.Empty;
        public uint SecurityID = 0;
        public object SecurityObj = null;
        public DateTime TimeStamp = DateTime.MinValue;
        public Type Type;
        public double Price = 0;
        public uint Size = 0;
        public Dictionary<string, string> Codes;
    }
}

我想在 F# 中创建它的一个实例。我用来执行此操作的代码位于 f# 脚本文件中

#r @"C:\Users\Chris\Documents\Visual Studio 2012\Projects\WranglerDataStructures\bin\Debug\WranglerDataStructures.dll"

open System
open System.Collections.Generic;
open System.Text;
open DataWrangler.Structures

type tick = TickData // <- mouse over the "tick" gives me a tooltip with the class structure

// it bombs out on this line 
let tickDataTest = tick(Security = "test", TimeStamp = DateTime(2013,7,1,0,0,0), Type = Type.Trade, Price = float 123, Size = uint32 10 )

我得到的错误是:

error FS0193: internal error: Could not load file or assembly 'file:///C:\Users\Chris\Documents\Visual Studio 2012\Projects\WranglerDataStructures\bin\Debug\WranglerDataStructures.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.

我检查了文件路径,它们似乎是正确的。我可以将鼠标悬停在“类型刻度”上,它为我提供了 C# 对象的结构。所以它似乎正在寻找 C# 代码。谁能告诉我我在这里做错了什么?句法?对 C# 还是很陌生 -> F# introp

【问题讨论】:

  • 我可以毫无问题地运行您的代码。也许你忘记了 alt+输入#r 到 F# 交互?
  • 不。当我点击那条线时,它给了我正确的反馈:Referenced 'C:\Users\Chris\Documents\Visual Studio 2012\Projects\WranglerDataStructures\bin\Debug\WranglerDataStructures.dll'
  • 如何删除type tick 并使用new TickData 创建对象实例?
  • "试图加载格式不正确的程序。"会不会是两个项目中x86/x64/Any CPU编译设置不兼容?
  • Joel(和 John #1)拥有它 - FSI 默认以 64 位模式运行,如果您尝试加载/使用 x86 程序集(来自 C#、F#、VB,...)你会看到这个错误。更改 FSI 或程序集的位数设置。

标签: syntax f# f#-interactive c#-to-f#


【解决方案1】:

这里有几件事要检查:

  1. 确保 fsi.exe 以与 WranglerDataStructures.dll 兼容的位模式运行。通过在 Visual Studio 选项中的 F# 工具 -> F# 交互 -> 64 位 F# 交互下设置标志,将 fsi.exe 作为 64 位或 32 位进程运行。您通常可以通过将 C# 程序集设置为编译为 Any CPU 来避免这些类型的问题。

  2. 确保 WranglerDataStructures.dll 不依赖于您未从 F# 引用的其他库。在 F# 中添加引用,或从 WranglerDataStructures.dll 中删除它们。

如果这些步骤没有成功,请尝试使用 fuslogview.exe 工具 http://msdn.microsoft.com/en-us/library/e74a18c4.aspx 来查看未加载的确切引用。

【讨论】:

  • 谢谢约翰!这确实是问题所在。我的 C# dll 是 64x。只需将 FSI 更改为以 64 倍运行。
最近更新 更多