【问题标题】:What are benefits of C# interfaces [duplicate]C#接口有什么好处[重复]
【发布时间】:2018-02-14 17:09:20
【问题描述】:

我已经使用接口完成了演示实现:

class Program
{
    static void Main(string[] args)
    {

        #region Calling method without interface
        GreaterThanZeroTest objGreaterThanZeroTest = new GreaterThanZeroTest { SomeTestVariable = 10 };
        Console.WriteLine(objGreaterThanZeroTest.SomeTestMethod().ToString());

        LessThanZeroTest objLessThanZeroTest = new LessThanZeroTest { SomeTestVariable = -1 };
        Console.WriteLine(objLessThanZeroTest.SomeTestMethod().ToString()); 
        #endregion

        #region Calling using interface
        runTest(new GreaterThanZeroTest() { SomeTestVariable = 10 });
        runTest(new LessThanZeroTest() { SomeTestVariable = 10 }); 
        #endregion

        Console.ReadKey();
    }

    public static bool runTest(ITest test)
    {
        return test.SomeTestMethod();
    }
}

public interface ITest
{
    int SomeTestVariable { get; set; }

    bool SomeTestMethod();
}

// Determines whether an int is greater than zero
public class GreaterThanZeroTest : ITest
{
    public int SomeTestVariable { get; set; }

    public bool SomeTestMethod()
    {
        return SomeTestVariable > 0;
    }
}

// Determines whether an int is less than zero
public class LessThanZeroTest : ITest
{
    public int SomeTestVariable { get; set; }

    public bool SomeTestMethod()
    {
        return SomeTestVariable < 0;
    }
}

我看到上述实现有两个好处:

  1. 代码看起来很干净。
  2. 它将节省一行代码。

我们将从这种实现中获得哪些其他好处,以及我们何时应该在应用程序架构中考虑接口?

【问题讨论】:

标签: c#


【解决方案1】:

恕我直言,对我来说最重要的是它可以让你

  1. 模拟某些功能以进行单元测试。
  2. 它允许实现“控制反转”或 IoC

宇宙中有很多你可以搜索的原因,但这些都是我认为重要的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多