[英]F# access protected field from a C# inherited class
我在C#中有一个看起来像这样的类:
class A {
protected SomeClass Field;
}
class B: A {}
以及F#中的以下代码:
type C() =
inherit B()
member this.SomeMethod() =
let magic() = base.Field.SomeMoreMagic(someParam) //this.Field also fails
...
我要在其中访问受保护的字段Field
。 我知道我可以通过简单类型base.something
访问B类的受保护字段( 在此处也得到回答 ),但是当我键入base.Field
访问A类的受保护字段时,我得到一个错误,指出struct or class field is not accessible from this code location
,因为Field
在类A(?)中声明。 我的问题是,是否有可能访问它?
我找到了解决我问题的方法。 这样的代码是不正确的:
type C() =
inherit B()
member this.SomeMethod() =
let d() = base.Field.SomeMagic(someParameter) //this.Field also fails
d()
但是这样的代码可以正常工作:
type C() =
inherit B()
member this.SomeMethod() =
let stub = this.Field
let d() = stub.SomeMagic(someParameter)
d()
存根解决方案之所以起作用,是因为您试图访问让绑定函数d
内的受保护字段。 这些函数将移出它们定义的上下文之外,并编译为FSharpFunc
类型的子类型。 也就是说,在已编译的F#代码(简化的图片)中会得到如下所示的内容:
internal class d@11 : FSharpFunc<Unit, int>
{
public C @this;
internal d@11(C @this)
{
this.@this = @this;
}
public override int Invoke(Unit unitVar0)
{
// this would be an attempt to access the protected field
// if the compiler allowed it.
return @this.Field.SomeMoreMagic();
}
}
public class C : B
{
public int SomeMethod()
{
FSharpFunc<Unit, int> d = new d@11(this);
return d.Invoke(null);
}
}
这意味着您尝试访问protected字段的代码块不再是C
类的一部分,而且protected
修饰符阻止了对该类的访问。
而如果将值绑定到d
之外,则会得到以下内容:
public class C : B
{
public int SomeMethod()
{
SomeClass stub = this.Field;
FSharpFunc<Unit, int> d = new d@11(stub);
return d.Invoke(null);
}
}
并且在C
类之外不再发生受保护的访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.