generics - 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..... } }
解决方案
推荐阅读
- reactjs - jest not implemented window.alert()
- java - Why are ArrayList created with empty elements array but HashSet with null table?
- python - local variable 'Postive_Points' referenced before assignment
- c# - The more you add hours to a DateTime class the more time you loss
- reinforcement-learning - Limit on Action Change in reinforcement learning
- c++ - unordered_set 与链表查找之间的性能比较
- etl - tPartitioner, tCollector & tRecollector talend DI
- sqlite - 简单的 Flutter sqflite login->write to db->navigate->retrieve from db flow
- c++ - 排序算法和对象指针的问题
- javascript - Why is non-reachable part of ternary operator evaluated before state update via setTimeout?