c#如何从另一个类中调用一个类中的接口方法?

时间:2018-10-22 13:19:51

标签: c# interface

我创建了一个类库,我想从Form1.SuccessfullActivation()调用一个方法(例如LicenceManager),所以我的问题是:

  1. 是否可以通过接口执行此操作?
  2. 如果可以,我该怎么做?
  3. 如果没有,最好的方法是什么?

在类库中,我有注册和/或验证产品注册的方法,并且我想在此dll之外调用方法,例如,EnableOrDisableFeatures的值首先为false,它的用途是以某种形式禁用控件;或FailedActivation用于关闭应用程序并警告用户。这就是为什么我需要从dll调用方法的原因。而且我强调类目录是一个独立的项目,该项目将嵌入到其他项目中,因此我不能调用诸如Form1.SuccessfullActivation()之类的方法。

代码

课程库

public interface ILicenceManager
{
    void EnableOrDisableFeatures(bool state);
    void SuccessfullActivation();
    void FailedActivation();
}
public class LicenceManager
{
    public LicenceManager()
    {
        //Call (for example) SuccessfullActivation() from here
    }
}

嵌入该dll的项目

public partial class Form1 : Form, ILicenceManager
{
     public Form1()
     {
         new LicenceManager();
     }
    public void EnableOrDisableFeatures(bool state)
    {
        throw new NotImplementedException();
    }

    public void SuccessfullActivation()
    {
        throw new NotImplementedException();
    }

    public void FailedActivation()
    {
        throw new NotImplementedException();
    }
}

2 个答案:

答案 0 :(得分:3)

正如一些评论所表明的那样,我认为您的观点不对。这是您可以使用的一种方法:

public interface ILicenseManager
{
    ...
}

public class LicenseManager: ILicenseManager
{
    // must implement all ILicenseManager methods
}

public partial class Form1: Form1
{
    private readonly ILicenseManager _licenseManager;

    public Form1()
    {
        _licenseManager = new LicenseManager();
    }        
}

现在您的表单可以引用实现LicenseManager的{​​{1}},并且您可以在需要时在表单中调用该对象上的方法。

答案 1 :(得分:2)

您可以使用constructor injection(一种依赖注入)来获取表单中的LicenceManager功能:

public interface ILicenceManager
{
    void EnableOrDisableFeatures(bool state);
    void SuccessfullActivation();
    void FailedActivation();
}

public class LicenceManager : ILicenceManager
{
    // insert implementation here
}

public partial class Form1 : Form
{
    private ILicenceManager _licenceManager;

    // Provide the implementation when calling the constructor e.g.:
    // new Form1(new LicenceManager());
    public Form1(ILicenceManager licenceManager)
    {
        this._licenceManager = licenceManager;
        // now you can make calls on this instance, e.g.
        // this._licenceManager.FailedActivation();
    }
}