【问题标题】:F# Inherit from C# class + access protected fieldsF# 从 C# 类继承 + 访问受保护的字段
【发布时间】:2013-03-01 05:21:15
【问题描述】:

我有这个基类,它创建一个新的 SQL Server 连接并在 C# 中执行一些实用程序方法,我想在 F# 中继承。目前我无法从 F# 访问 C# 类中的受保护字段,尽管这可以在 C# 中工作。

C#抽象类

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# 代码

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

我在这里错过了什么吗?我试过给基类字段起别名,例如this.conn 也不起作用。

谢谢 理查德

【问题讨论】:

    标签: inheritance f# protected


    【解决方案1】:

    您可以在构造函数中添加自标识符:

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

    或者,使用base 关键字:

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

    【讨论】:

      【解决方案2】:

      查看相关问题:

      基本上我认为您不能在 let 中执行此操作,因为它实际上是在隐式 lambda 的上下文中。

      【讨论】:

      • 是的,看起来是这样,查看 Daniel 使用别名调用类的代码确实可以访问所有成员,包括继承的成员。但是我无法访问这些字段。那么如何更改连接字段的属性呢?
      • @RichardTodd:我的回答中的两种方法提供对所有受保护成员的访问,包括字段。
      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 2010-09-14
      • 2013-03-13
      • 2019-05-16
      • 1970-01-01
      • 2011-05-24
      • 2020-11-02
      • 2012-05-26
      相关资源
      最近更新 更多