gpt4 book ai didi

c# - 在 F# 语言中覆盖 C# 类中的方法会使该方法不可自省(introspection)?

转载 作者:太空狗 更新时间:2023-10-30 00:31:58 26 4
gpt4 key购买 nike

我有以下 C# 类:

public class Foo {
protected virtual void Bar (){
}
}

public class Baz : Foo {
protected override void Bar (){
}
}

如果我反省它们,方法 Bar 总是存在的:

[<EntryPoint>]
let main args =
let methodFromFoo = typedefof<Foo>.GetMethod("Bar", BindingFlags.Instance ||| BindingFlags.NonPublic)
if (methodFromFoo <> null) then
Console.WriteLine ("methodFromFoo is not null")
else
Console.WriteLine ("methodFromFoo is null")

let methodFromBaz = typedefof<Baz>.GetMethod("Bar", BindingFlags.Instance ||| BindingFlags.NonPublic)
if (methodFromBaz <> null) then
Console.WriteLine ("methodFromBaz is not null")
else
Console.WriteLine ("methodFromBaz is null")

这两种情况的结果都是不为空

但是,当我对 F# 类执行相同操作时,结果不同:

type FSharpBaz() =
inherit Foo()
override this.Bar () =
Console.WriteLine ("yeh")

[<EntryPoint>]
let main args =
let methodFromFsharp = typedefof<FSharpBaz>.GetMethod("Bar", BindingFlags.Instance ||| BindingFlags.NonPublic)
if (methodFromFsharp <> null) then
Console.WriteLine ("methodFromFsharp is not null")
else
Console.WriteLine ("methodFromFsharp is null")

但是为什么???如果我的类是用 F# 创建的,我不能通过反射获取方法吗?我很伤心。

最佳答案

您看不到它的原因是因为 FSharpBaz.Bar 是作为 public 而不是 protected 发出的。您可以通过查看 ildasm 中的代码来验证这一点。这实际上是完全合法的行为,在 CLI 规范的第 8.5.3.2 节中有介绍

When a type defines a virtual method that overrides an inherited definition, the accessibility shall either be identical in the two definitions or the overriding definition shall permit more access than the original definition.

至于为什么F#在这里使用public,那只是成员定义的默认值

If no access specifier is used, the default is public, except for let bindings in a type, which are always private to the type (Link)

关于c# - 在 F# 语言中覆盖 C# 类中的方法会使该方法不可自省(introspection)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21026927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com