Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 接口如何成为类中的变量?_C#_Interface - Fatal编程技术网

C# 接口如何成为类中的变量?

C# 接口如何成为类中的变量?,c#,interface,C#,Interface,我试图理解一个项目中的类,但对接口有点困惑。 根据我的理解,接口是一个特定类将遵守的“契约”,因此它将始终为指定的方法、属性等提供实现 那么,我怎么可能把它作为一个对象来实现呢?比如说 private IMyInterfaceName _interfaceObject; 有人能解释一下接口作为对象的目的是什么以及如何使用它吗?\u interfaceObject能够保存对实现接口的类实例的引用: public class MyClass : IMyInterfaceName {} 这是一份

我试图理解一个项目中的类,但对接口有点困惑。 根据我的理解,接口是一个特定类将遵守的“契约”,因此它将始终为指定的方法、属性等提供实现

那么,我怎么可能把它作为一个对象来实现呢?比如说

private IMyInterfaceName _interfaceObject;

有人能解释一下接口作为对象的目的是什么以及如何使用它吗?

\u interfaceObject
能够保存对实现接口的类实例的引用:

public class MyClass : IMyInterfaceName {}


这是一份包含两个实现的合同:

interface ICalculator 
{
    //this contract makes it possible to add to given numbers a and b
    int Add(int a, int b);
}

class SmartCalculator : ICalculator
{
    // a concise way to add two numbers
    public int Add(int a, int b)
    {
        return a+b;
    }
}

class DumbCalculator : ICalculator
{
    //A not that beautiful way to add to numbers
    public int Add(int a, int b)
    {
        int result = a;
        for(var i=1;i<=b;i++)
        {
            result+=1;
        }
        return result;
    }
}

约翰·桑德斯给出了正确的解释。上面的问题没有回答我的问题,因为它解释了什么是接口,而我并没有问这个问题。我不确定为什么所有的反对票都是真实的,因为我的问题表明我已经研究了什么是接口。
interface ICalculator 
{
    //this contract makes it possible to add to given numbers a and b
    int Add(int a, int b);
}

class SmartCalculator : ICalculator
{
    // a concise way to add two numbers
    public int Add(int a, int b)
    {
        return a+b;
    }
}

class DumbCalculator : ICalculator
{
    //A not that beautiful way to add to numbers
    public int Add(int a, int b)
    {
        int result = a;
        for(var i=1;i<=b;i++)
        {
            result+=1;
        }
        return result;
    }
}
class MyMainClass
{
    private readonly ICalculator calcuator;

    public MyClass()
    {
        //If I'm smart i'll do the following
        calculator = new SmartCalculator();
        //If I'm not, well..
        calculator = new DumbCalculator();
    }
}