[英]F# type extensions in C# project: System.Runtime.CompilerServices.Extension missed?
I'm diving into F# and it's very fascinating. 我正在研究F#,这非常令人着迷。 I'm trying to marry Optional Types and C# like here . 我想像这里将Optional Types和C#结合起来。 Pretty interesting thing... however I miss something important I guess: 非常有趣的事情...但是我想念一些重要的事情:
#light
namespace MyFSharp
// C# way
[<System.Runtime.CompilerServices.Extension>]
module ExtensionMethods =
[<System.Runtime.CompilerServices.Extension>]
let Great(s : System.String) = "Great"
using System;
using MyFSharp; // reference the F# dll
class Program
{
static void Main(string[] args)
{
var s = "foo";
//s.Awesome(); // no
Console.WriteLine(s.Great()); // yes
}
}
That's very simple - and I guess it's too early for me or something... I get: 这很简单-我想这对我来说还为时过早...我得到了:
The type 'Extension' is not defined
Maybe it's too early... but I just don't get why it isn't found. 也许还为时过早...但是我不明白为什么找不到它。
Thanks, Marius 谢谢,马吕斯
Does your F# project have a reference to the System.Core
assembly? 您的F#项目是否有对System.Core
程序集的引用?
EDIT: Hmm... perhaps explicitly call it ExtensionAttribute
instead of just Extension
? 编辑:嗯...也许明确地将其称为ExtensionAttribute
而不只是Extension
? Maybe if the namespace is specified (instead of just a simple name) it doesn't try with the Attribute
suffix? 也许如果指定了名称空间(而不只是一个简单的名称),它是否不尝试使用Attribute
后缀?
Extension methods need to be static in a static class. 扩展方法在静态类中必须是静态的。 Does F# actually emit it as such? F#是否真的这样发出它? If not, then you are out of luck. 如果没有,那么您就不走运了。
Update 更新资料
I just tried it, and it appears to emit static class and method. 我只是尝试过,它似乎发出了静态的类和方法。 I got the same error as you, but fixed by compiling as: 我遇到了与您相同的错误,但是通过编译为:
fsc -r System.Core test.fs fsc -r System.Core test.fs
Then looking at the output of the assembly in Reflector, it looks all good and should work. 然后在Reflector中查看程序集的输出,看起来一切正常,应该可以工作。
Sounds like your F# project is targeting the .Net Framework 2.0. 听起来您的F#项目以.Net Framework 2.0为目标。
Try changing it to .Net Framework 3.5 (under the project properties -> Application). 尝试将其更改为.Net Framework 3.5(在项目属性->应用程序下)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.