是否使用泛型?

编程入门 行业动态 更新时间:2024-10-26 20:35:22
本文介绍了是否使用泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有一个关于是否使用泛型的简单问题,如果可以,这是正确的方法吗?

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.

更多推荐

是否使用泛型?

本文发布于:2023-11-16 17:28:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!