Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.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#_.net_Class_Methods_Interface - Fatal编程技术网

C# 为什么我应该使用接口,而不是在没有接口的类中直接声明方法

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

你们能解释一下为什么我真的需要使用接口,而不是直接在类内部声明和实现方法吗。上面我有两个例子。使用接口和不使用接口初始化。提前谢谢

示例1我为什么要使用此选项

示例2为什么我不应该使用这个


你没有理由不使用第二个,你的实际用例是什么?我会在谷歌上搜索
类与接口之间的区别这会让你更好地理解
什么时候以及为什么不使用第二个,你的实际使用案例是什么?我会在谷歌上搜索
类与接口之间的区别
,这会让你更好地理解
何时以及为什么
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();
        }
    }