【问题标题】:How to return an object that implements an interface from a method如何从方法返回实现接口的对象
【发布时间】:2009-11-12 20:39:09
【问题描述】:

我正在尝试学习接口并想尝试以下方法:

假设我有一个名为 ICustomer 的接口,它定义了基本属性(UserID、UserName 等)。现在,我有多个具体的类,如 ProductA_User、ProductB_User、ProductC_User。每个都有不同的属性,但它们都实现了 ICustomer,因为它们都是客户。

我想在一个名为 MemberFactory 的工厂类中调用一个共享方法,并告诉它给我一个新用户,我只是给它一个我想要的枚举值的参数。由于每个具体类都不同但实现了 ICustomer,我应该能够返回一个实现 ICustomer 的实例。但是,我不确定如何在工厂类中执行此操作,因为我的返回类型是 ICustomer。

【问题讨论】:

  • .NET 中的接口注意事项:它们可以用作对象类型。因此,如果两个随机对象(汽车和电话)都实现了接口 ILike,则可以通过将 ILike 指定为函数的返回类型来让函数返回任一类型。

标签: c# interface


【解决方案1】:

你所要做的就是像这样创建你的对象:

class ProductA_User : ICustomer
{
    //... implement ICustomer
}
class ProductB_User : ICustomer
{
    //... implement ICustomer
}
class ProductC_User : ICustomer
{
    //... implement ICustomer
}

class MemberFactory 
{
     ICustomer Create(ProductTypeEnum productType)
     {
         switch(productType)
         {
             case ProductTypeEnum.ProductA: return new ProductA_User();
             case ProductTypeEnum.ProductB: return new ProductB_User();
             case ProductTypeEnum.ProductC: return new ProductC_User();
             default: return null;
         }
     }
}

【讨论】:

  • 有道理!感谢您的帮助!
【解决方案2】:

当您调用该方法时,您所要做的就是正常返回对象。它将它映射到它发挥作用的界面。

ICustomer obj = MemberFactory.ReturnObjectWhichImplementsICustomer();

【讨论】:

    【解决方案3】:

    工厂方法包含的代码大致如下:

    switch (customerType)
    {
    case CustomerType.A:
       return new ProductA_User();
    case CustomerType.B:
       return new ProductB_User();
    case CustomerType.C:
       return new ProductC_User();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 2021-01-18
      • 2015-01-01
      • 2013-08-16
      • 1970-01-01
      • 2015-03-29
      • 1970-01-01
      相关资源
      最近更新 更多