是否可以将抽象类的对象作为参数传递给类的实例?

时间:2013-07-28 18:14:22

标签: c# abstract

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

看看“新的DealerAccountRepository(MyEnvironmentSetting);” “DatabaseDataDealer”类中的部分。

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...
}

1 个答案:

答案 0 :(得分:1)

如果你问一个方法是否可以采用这样的抽象对象:

private void DoSomething(AEnvironmentSetting a)

然后是的,它可以,你可以使用抽象类中的每个属性和方法,包括调用抽象方法。 但是,无论谁调用此方法都必须发送一个calss实例继承抽象类,如下所示:

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

如果从DoSomething调用抽象方法,则会调用DatabaseDataDealer的实现

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