我接近于接口顿悟

drp*_*ken 4 c# asp.net oop visual-studio

我总是在接口处缠绕问题,所以我尽力避免它们.直到我看到这段代码

public interface IFormsAuthenticationService
{
    void SignIn(string userName, bool createPersistentCookie);
    void SignOut();
}

public class FormsAuthenticationService : IFormsAuthenticationService
{
    public void SignIn(string userName, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");

        FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    }

    public void SignOut()
    {
        FormsAuthentication.SignOut();
    }
}
Run Code Online (Sandbox Code Playgroud)

看着这个我收集到的IFormsAuthenticationServce界面或多或少是这个FormsAuthenticationService类的"蓝图" 吧?但为什么?对我而言似乎是多余的.我知道它不是,但我不明白为什么它有益,为什么你应该为你的类创建接口.它仅用于预先确定类的方法吗?

Pet*_*ete 7

它仅用于预先确定类的方法吗?

不是.重点是允许将使用接口的代码编码到接口,而不是特定的实现.优点是,当您想要以其他方式实现IFormsAuthenticationService时,您不需要更改使用该接口的代码,只需传递实现现有"合同"的其他类.