有一个关于是否使用泛型的简单问题,如果可以,这是正确的方法吗?
Got a simple question regarding whether to use generics or not and if yes, is this the right way?
正常的非通用版本如下:
The normal non-generic version is as below:
public interface IFood { string name { get; set; } } public class Vegetables : IFood { #region IFood Members public string name { get { return "Cabbage"; } set{ } } #endregion } public class Cow { private IFood _food; public Cow(IFood food) { _food = food; } public string Eat() { return "I am eating " + _food.name; } }通用版本如下:
public class Cow<T> where T : IFood { private T _food; public Cow(T food) { _food = food } public string Eat() { return "I am eating " + _food.name; } }我可以在通用版本中正确执行所有操作吗?是否有必要使用通用版本以实现未来的增长?这只是原始场景的简单模型,但完全相似.
Am I doing everything right in generic version? Is it necessary to use Generic version for future growth? This is just the simple mock up of the original scenario but it resembles completely.
推荐答案在这个特定示例中,我认为这是个坏主意.
I think its a bad idea in this specific example.
List< int> 通常被描述为int的List. Cow< IFood> 很难描述-它当然不是IFood的母牛.这不是扣篮论据,但显示出潜在的问题.
A List<int> is often described as List of int. A Cow<IFood> is harder to describe - it certainly isn't a Cow of IFood. This isn't a slam dunk argument, but shows a potential problem.
MSDN 状态:
使用泛型类型来最大化代码重用,类型安全性和性能.
Use generic types to maximize code reuse, type safety, and performance.
在您的示例中,通用版本不再重复使用代码,不再具有类型安全性并且没有改进的性能.
In your example, the generic version has no more code reuse, no more type safety and no improved performance.
更多推荐
是否使用泛型?
发布评论