使方法通用 [英] Making a method generic

查看:67
本文介绍了使方法通用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,


我想为其他属性制作以下方法通用,例如Product Id,ProductType,ProductCategory ... ie我需要能够通过任何这些属性作为此方法的参数,它应该从
集合中返回相应的值。

private string GetABC()

{

   返回myList.Select(x => x.ProductName)

}


除了切换案例外,还有更好的方法可以在C#中实现吗?


谢谢。

解决方案

我想说你不需要。 LINQ已经有了select语句,因此在它周围放置一个包装器不会获得任何东西。只需使用LINQ。如果您想要执行常见查询,请添加专注于特定
详细信息的扩展方法。

 public static class ProductExtensions 
{
public static IEnumerable< Product> GetProductsByName(此IEnumerable< Product>源,字符串productName)
{
return source.Select(x => x.ProductName == productName);
}
}

在您的具体示例中,您编写了一个返回属性的方法。你为什么要直接使用这个属性呢?

 Product product = ...; 

//这有什么收获?
var name = GetABC();

// vs这个
var name2 = product.ProductName;

你的方法实际上有点混乱,因为你使用的是Select返回IEnumerable< string>但是你要返回一个字符串。这甚至都不应该编译。


关于使你的方法具有通用性的一般问题,那么你可以,但是,为什么呢?

 //未测试
private T Get< T> (Func< Product,T> getter)
{
return myList.Select(getter).FirstOrDefault();
}




Hello,

I want to make following method generic for other attributes as well, like Product Id, ProductType, ProductCategory...i.e.I need to be able to pass any of these attributes as a parameter to this method and it should return the corresponding value from the collection.
private string GetABC()
{
    return myList.Select(x=>x.ProductName)
}

Is there any better way of achieving this in C# other than switch case please?

Thanks.

解决方案

I would say you don't need to. LINQ already has the select statement so putting a wrapper around it wouldn't gain you anything. Just use LINQ. If there are common queries you want to do then add extension methods instead that are focused on the specific details.

public static class ProductExtensions
{
   public static IEnumerable<Product> GetProductsByName ( this IEnumerable<Product> source, string productName )
   {
       return source.Select(x => x.ProductName == productName);
   }
}

In your specific example you have written a method that returns a property. Why would you do this vs just using the property directly.

Product product = ...;

//What does this gain you?
var name = GetABC();

//vs this
var name2 = product.ProductName;

Your method is actually a little confusing because you are using Select which returns back IEnumerable<string> but you're returning a string. This shouldn't even compile.

As for the general question of making your method generic then yes you could but, again, why?

//Not tested
private T Get<T> ( Func<Product, T> getter )
{
   return myList.Select(getter).FirstOrDefault();
}


这篇关于使方法通用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆