简体   繁体   English

如何从方法返回实现接口的对象

[英]How to return an object that implements an interface from a method

I'm trying to learn interfaces and want to try the following: 我正在尝试学习接口,并想尝试以下方法:

Let's say I have an interface named ICustomer that defines basic properties (UserID, UserName, etc). 假设我有一个名为ICustomer的接口,它定义了基本属性(UserID,UserName等)。 Now, I have multiple concrete classes like ProductA_User, ProductB_User, ProductC_User. 现在,我有多个具体的类,如ProductA_User,ProductB_User,ProductC_User。 Each one has different properties but they all implement ICustomer as they are all customers. 每个人都有不同的属性,但他们都是ICustomer,因为他们都是客户。

I want to invoke a shared method in a factory class named MemberFactory and tell it to new me up a user and I just give it a param of the enum value of which one I want. 我想在一个名为MemberFactory的工厂类中调用一个共享方法,并告诉它新用户,我只是给它一个我想要的枚举值的参数。 Since each concrete class is different but implements ICustomer, I should be able to return an instance that implements ICustomer. 由于每个具体类都不同但实现了ICustomer,我应该能够返回一个实现ICustomer的实例。 However, I'm not exactly sure how to do it in the factory class as my return type is ICustomer. 但是,我不确定如何在工厂类中执行此操作,因为我的返回类型是ICustomer。

All you have to do is create your object like this: 你所要做的就是像这样创建你的对象:

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

When you call the method all you have to do is return the object as normal. 当你调用方法时,你所要做的就是正常返回对象。 It's mapping it to the interface where it comes into play. 它将它映射到它发挥作用的界面。

ICustomer obj = MemberFactory.ReturnObjectWhichImplementsICustomer();

The factory method would include code that does something roughly like this: 工厂方法将包含执行大致类似的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM