首页 > 解决方案 > C# 直接实现泛型参数化类

问题描述

假设我正在为一个应用程序实现代码,该应用程序允许用户为他们的手机购买保护套。

在此处输入图像描述

保护套<T>

类,我需要添加对每种类型的手机都是唯一的特定代码。

例如,我可能有如下代码:

public void UseMaterial(string materialSpec){

     Type itemType = typeof(T);
     if (itemType == typeof(IPhone)){
           .....blah blah add extra protective layering.....
     }
     else if  (itemType == typeof(Samsung)){
           ....blah blah add inner metal shield plate.....
     }
     else if  (....blah....blah...
}

现在的代码

保护套<T>

类有很多 if then “If-Else-If 语句”,看起来真的很不优雅和/或不成熟。有人可以告诉我可以直接实现类的代码吗

ProtectiveCase<IPhone>类

,

ProtectiveCase<三星>类

, ETC。 ?换句话说,在 C# 中是否有可能拥有像下面这样的单独的类?

public class ProtectiveCase<IPhone>
{  
  public void UseMaterial(string materialSpec){
        .....blah blah add extra protective layering.....
   }

}


public class ProtectiveCase<Samsung>
{  
  public void UseMaterial(string materialSpec){
       ....blah blah add inner metal shield plate.....
   }

}

标签: genericsinheritanceparametersinterfaceparameterized

解决方案


推荐阅读