gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:36 25 4
gpt4 key购买 nike

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

看看“new 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...
}

最佳答案

如果你问一个方法是否可以像这样接受一个抽象对象:

private void DoSomething(AEnvironmentSetting a)

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

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

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

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

关于c# - 是否可以将抽象类的对象作为参数传递给类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17911285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com