C# 为什么我应该使用接口,而不是在没有接口的类中直接声明方法
你们能解释一下为什么我真的需要使用接口,而不是直接在类内部声明和实现方法吗。上面我有两个例子。使用接口和不使用接口初始化。提前谢谢 示例1我为什么要使用此选项 示例2为什么我不应该使用这个C# 为什么我应该使用接口,而不是在没有接口的类中直接声明方法,c#,.net,class,methods,interface,C#,.net,Class,Methods,Interface,你们能解释一下为什么我真的需要使用接口,而不是直接在类内部声明和实现方法吗。上面我有两个例子。使用接口和不使用接口初始化。提前谢谢 示例1我为什么要使用此选项 示例2为什么我不应该使用这个 你没有理由不使用第二个,你的实际用例是什么?我会在谷歌上搜索类与接口之间的区别这会让你更好地理解什么时候以及为什么不使用第二个,你的实际使用案例是什么?我会在谷歌上搜索类与接口之间的区别,这会让你更好地理解何时以及为什么 interface ISampleInterface { void Sample
你没有理由不使用第二个,你的实际用例是什么?我会在谷歌上搜索
类与接口之间的区别这会让你更好地理解什么时候以及为什么不使用第二个,你的实际使用案例是什么?我会在谷歌上搜索类与接口之间的区别
,这会让你更好地理解何时以及为什么
interface ISampleInterface
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}
static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
}
class ImplementationClass
{
void SampleMethod()
{
// Method implementation.
}
static void Main()
{
// Declare an interface instance.
ImplementationClass obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
}