在.net中使用接口实例化和派生类实例化的区别是什么?

本文关键字:实例化 区别 是什么 派生 接口 net | 更新日期: 2023-09-27 18:09:53

interface Icustomer
{
    void sample();
}
public  class customer : Icustomer
{
   public void sample()
    {
        Console.WriteLine("This is sample Method");
    }
}
class Program
{
    static void Main()
    {
       Icustomer ob1 = new customer();
        customer ob2 = new customer();
    }

在.net中使用接口实例化和派生类实例化的区别是什么?

对于您的特定示例,没有区别,但是针对Interface变量进行实例化非常有用,因为它有助于编写具体的实例化独立代码。

例如

interface IPizza {    
    public String Bake();  }  
public class CountrySpecial: IPizza   {
     public String Bake() 
     {
      //add country special toppings 
     } }
public class FarmHouse: IPizza   {
     public String Bake()
     { 
     //add farm house special toppings 
     } }
public class Order   {
    public void PlaceOrder(IPizza pizza) 
    {
     pizza.Bake(); 
     //pack and ship 
    } }
现在你可以做一些神奇的事情而不依赖于具体的初始化,比如:
class Program
{
    static void Main()
    {
       Order ord = new Order(); 
       //customer ordered for country special
       ord.PlaceOrder(new CountrySpecial()); //this will call bake of CountrySpecial
       //maybe some other customer ordered for different pizza, and we can change at run-time(thanks to our design!)
       ord.PlaceOrder(new FarmHouse()); // this will call Bake of FarmHouse
    }
}
在上述设计的帮助下,我们可以添加尽可能多的比萨饼类型,而无需更改订购代码!

另外,虽然你在。net的背景下问,但它与语言无关,因为它是一个设计问题;)

我希望它可以帮助!

不同的想法。这样记住它。接口是一种契约,因此您和其他第三方可以为同一任务开发相互竞争的服务。

是一个派生类,你正在使用别人的实现,假设你没有覆盖一个虚拟。

在第一种情况下,您只能访问接口iccustomer声明的方法和属性。在第二种情况下,您可以访问客户类的所有方法、属性和字段。

用interface声明变量的真正好处是你可以用任何实现它的类实例化它。

实现客户接口的两个类的示例

public class customerA : Icustomer
public class customerB : Icustomer

你可以像这样实例化例如

Icustomer c;
if (test)
    c = new customerA();
else
    c = new customerB();
c.sample();

这是多态性的定义