【问题标题】:Nullable values do not get modified when passed into C# code by reference通过引用传递到 C# 代码时不会修改可空值
【发布时间】:2009-03-16 14:39:59
【问题描述】:

我有一个 F# 变量定义如下

let id = new Nullable<int>()

我将它从 F# 传递到一个 C# 函数,该函数接受 ref Nullable&lt;int&gt;,然后为其分配一个值(它基本上是由 Linq2Sql 自动生成的存储过程代码)。

不幸的是,当函数调用退出时,我的id 变量仍然没有值(即为空)。我尝试将其声明为mutable,但 F# 抱怨我不能在闭包中使用可变变量。

有人可以帮忙吗?谢谢!

【问题讨论】:

    标签: c# interop f# null stored-procedures


    【解决方案1】:

    C#:

    namespace TestLibrary
    {
        public class TakesRefNullableInt
        {
            public void Foo(ref Nullable<int> ni)
            {
                ni = null;
            }
        }
    }
    

    F#:

    // mutable version
    let Main() =
        let mutable ni = new System.Nullable<int>(42)
        let tfni = new TestLibrary.TakesRefNullableInt()
        printfn "%A" ni
        tfni.Foo(&ni)
        printfn "%A" ni
    Main()
    
    // 'ref' version
    let Main2() =
        let ni = ref(new System.Nullable<int>(42))
        let tfni = new TestLibrary.TakesRefNullableInt()
        printfn "%A" !ni
        tfni.Foo(ni)
        printfn "%A" !ni
    Main2()
    

    (可能另见http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!677.entry

    【讨论】:

      猜你喜欢
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      相关资源
      最近更新 更多