简体   繁体   English

将参数传递给抽象 class 构造函数 c#

[英]Pass argument to abstract class constructor c#

I have an abstract class like below:我有一个抽象的 class 如下所示:

Public abstract class Test
{
    private readonly ILogger _logger;

    public Test(ILogger logger)
    {
        _logger = logger;
    }

    public ActionResult GetData()
    {
        try
        {

        }

        catch(Exception exe)

        {

            _logger.log("Exception");

        }
    }
}

Now, I have another class which uses the above in the below way:现在,我有另一个 class 以下列方式使用上述内容:

Public class TestProcess
{
    public Test tst {get; protected set;}

    public TestProcess(Test tesstt)
    {
        tst = tesstt;
    }
}

Now, I want to pass the ILogger to my abstract constructor from TestProcess class.现在,我想将ILoggerTestProcess class 传递给我的抽象构造函数。 Could someone help me out how can I do this?有人可以帮我解决这个问题吗?

Recommended to do following建议进行以下操作

Public class TestProcess:Test
{
    public ILogger _logger {get; set;}

    public TestProcess(ILogger logger): : base(logger)
    {
        _logger = logger;
    }
}

There are 2 ways to do this and in both you need to change your code littele bit.有两种方法可以做到这一点,在这两种方法中你都需要改变你的代码。

  1. Extendes your TestProcess class with Test(abstract) class.使用 Test(abstract) class 扩展您的 TestProcess class。

    public class TestProcess:Test{}公共 class 测试过程:测试{}

  2. Change your abstract class to normal class and implement singleton there.将您的抽象 class 更改为普通 class 并在那里实现 singleton。 then you can pass the ILogger while creating instance of Test class.那么您可以在创建测试 class 的实例时通过 ILogger。

    public class Test{}公共 class 测试{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM