Csharp/C#教程:仅基于返回类型重载分享


仅基于返回类型重载

我有一种情况,我想从这个函数返回List

public DataTable GetSubCategoriesBySubCatID(Guid SubCategoryID) 

所以我想要的是

 public List GetSubCategoriesBySubCatID(Guid SubCategoryID) 

我知道仅基于返回类型不支持重载,我只是不想在两个函数中复制相同的代码。

什么是实现这一目标的最佳方式,而不会影响第一个function的参考

给他们不同的免费精选名字大全:

 public DataTable GetSubCategoryTableBySubCatID(Guid subCatID) public List GetSubCategoryListBySubCatID(Guid subCatID) 

除了其他任何东西,这将使您在阅读调用代码时更清楚您感兴趣的方法。

如果这些应该以通用方式实现,请编写包含公共核心的私有方法,并从两个公共方法中调用它。 例如,您可以使用委托来执行“我已找到结果,将其添加到您的集合”部分,或使用迭代器块:

 // "action" will be called on each sub-category private void FindSubCategoriesBySubCatID(Guid subCatID, Action action) private IEnumerable FindSubCategoriesBySubCatID(Guid subCatID) 

使用如下的generics。

  public T GetSubCategoriesBySubCatID(Guid SubCategoryID) { T value = ...; return value; } 

我会定义

 public IEnumerable GetSubCategoriesBySubCatID(Guid SubCategoryID); 

此方法的实现类可以自由使用任何实现IEnumerable {SubCategories}的集合或容器

可以做到这就是这样

正如许多人已经解释过C#不支持返回类型重载。 事实上,它得到了CTS的支持。 但是使用接口并且如果应用程序中的场景绝对需要我们可以使用显式接口实现来模拟返回类型方法重载

我们可以定义两个具有相同方法签名但不同返回类型的接口,例如

 Interface I1 { DataTable GetSubCategoriesBySubCatID(Guid SubCategoryID); } Interface I2 { List GetSubCategoriesBySubCatID(Guid SubCategoryID); } 

我们定义了将实现这两​​个接口的类

 public class CategoryFinder:I1, I2 { public DataTable GetSubCategoriesBySubCatID(Guid SubCategoryID) //Implicitly implementing interface { //processing return _dt; } List I2.GetSubCategoriesBySubCatID(Guid SubCategoryID) //explicit implementing interface { //processing return _list<> } } 

由于CategoryFinder类实现了冲突的GetSubCategoriesBySubCatID,我们必须明确地对接口进行类型转换,如下所示

上述就是C#学习教程:仅基于返回类型重载分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 CategoryFinder cf = new CategoryFinder(); cf.GetSubCategoriesBySubCatID(Guid SubCategoryID); // will call the implicit return type which is data table ((I1)cf).GetSubCategoriesBySubCatID(Guid SubCategoryID); // will return **I1** implementation ie datatable ((I2)cf).GetSubCategoriesBySubCatID(Guid SubCategoryID); // will return **I2** implementation ie list 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1014748.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐