是否可以传递抽象类';s对象作为类实例的参数

本文关键字:对象 实例 参数 抽象类 是否 | 更新日期: 2023-09-27 18:25:10

我想知道是否可以将抽象类的属性(或函数)值传递给实例类参数?或者,我必须创建一个私有成员变量,将数据分配给它,然后将其传递给实例类参数?这听起来很令人困惑,所以下面的例子将有助于更好地阐明这一点。

查看"DatabaseDataDealer"类中的"new DealerAccountRepository(MyEnvironmentSetting);"部分。

public abstract class AEnvironmentSetting
{
    //Constructor...
    protected AEnvironmentSetting(EnvironmentSetting parmEnvironmentSetting)
    {
        _environmentSetting = new EnvironmentSetting
        {
            Emulation = parmEnvironmentSetting.Emulation, 
            Database = parmEnvironmentSetting.Database
        };
    }
    //Member variables...
    private EnvironmentSetting _environmentSetting = null;
    //Get/Set properties...
    protected string MyEmulation { get { return _environmentSetting.Emulation; } }  //No need for "set {}" property...
    protected string MyDatabase { get { return _environmentSetting.Database; } }  //No need for "set {}" property...
    //Functions...
    protected EnvironmentSetting MyEnvironmentSetting()
    {
        return _environmentSetting;
    }
}
public class DealerAccountRepository : AEnvironmentSetting
{
    //Constructor...
    public DealerAccountRepository(EnvironmentSetting parmEnvironmentSetting) : base(parmEnvironmentSetting)
    {
    }
    //Functions...
    public string Foo_Emulation()
    {
        return MyEmulation;  //This object coming from the abstract class "AEnvironmentSetting"...
    }
    public string Foo_Database()
    {
        return MyDatabase;  //This object coming from the abstract class "AEnvironmentSetting"...
    }
    public EnvironmentSetting Foo_EnvironmentSetting()
    {
        return MyEnvironmentSetting();  //This object coming from the abstract class "AEnvironmentSetting"...
    }
}
public class DatabaseDataDealer : AEnvironmentSetting
{
    //Constructor...
    public DatabaseDataDealer(EnvironmentSetting parmEnvironmentSetting) : base(parmEnvironmentSetting)
    {
    }
    //Get/Set properties...
    public DealerAccountRepository DealerAccount { get { return new DealerAccountRepository(MyEnvironmentSetting); } }  //No need for "set {}" property...
    //Functions...
    //N/A...
}

是否可以传递抽象类';s对象作为类实例的参数

如果您询问一个方法是否可以接受这样的抽象对象:

private void DoSomething(AEnvironmentSetting a)

是的,它可以,并且您可以使用抽象类中的每个属性和方法,包括调用抽象方法。然而,无论谁调用这个方法,都必须发送一个calss的实例,它继承了如下抽象类:

DatabaseDataDealer d = new DatabaseDataDealer ();
DoSomething(d);

如果将从DoSomething调用抽象方法,则DatabaseDataDealer的实现将被称为

在构造函数中,您可以调用基,然后您将获得抽象构造函数。最后,让我说,学习这一点的最好方法就是尝试。编译并运行您的代码,并设置一个断点来查看它是如何进行的以及经过了哪些步骤