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();
}
}