F# Inherit from C# class + access protected fields

浪子不回头ぞ 提交于 2019-12-01 22:18:55

问题


I have this base class that creates a new SQL Server connection and does some utility methods in C#, I want to inherit in F#. Currently I cannot access the protected fields in the C# class from F#, although this would work in C#.

C# abstract class

public abstract class SQL
{
    protected readonly SqlConnectionStringBuilder bld;
    protected readonly SqlCommand cmd;
    protected readonly SqlConnection conn;
    protected readonly string connstring;
    protected string userid;

    public SQL(string server, string db)
    {
        bld = new SqlConnectionStringBuilder();
        bld.DataSource = server;
        bld.InitialCatalog = db;
        bld.IntegratedSecurity = true;
        connstring = bld.ConnectionString;

        conn = new SqlConnection(connstring);
        cmd = new SqlCommand();

        GetUserID();
        //Other utility methods here
    }

F# code to inherit

type Transfer ( server : string ) ( db : string ) = 
inherit SQL(server, db)  
let accessAbstractConn = conn. //Can't access protected field????

Have I missed something here? I have tried aliasing the base class field e.g. this.conn which also does not work.

Thanks Richard


回答1:


You can add a self-identifier to the constructor:

type Transfer ( server : string, db : string ) as this = 
  inherit SQL(server, db)  
  let accessAbstractConn = this.conn

or, use the base keyword:

type Transfer ( server : string, db : string ) = 
  inherit SQL(server, db)  
  let accessAbstractConn = base.conn



回答2:


See related questions:

  • F# - How to access protected member

  • Why isn't there a protected access modifier in F#?

Basically I think you can't do it from within a let because it's actually in the context of an implicit lambda.



来源:https://stackoverflow.com/questions/15091468/f-inherit-from-c-sharp-class-access-protected-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!