开发者

Generalizing an extension method to work with any type

开发者 https://www.devze.com 2023-01-26 10:08 出处:网络
I am trying to generalize my \"La开发者_如何转开发st\" extension method to be used with a list of any data type:

I am trying to generalize my "La开发者_如何转开发st" extension method to be used with a list of any data type:

public static CartesianPoint Last(this List<CartesianPoint> MyList)
{
    return MyList.ElementAt(MyList.Count - 1);
}

"CartesionPoint" is a custom struct. I would like this function to work with a list of any data type. Is this possible? Is using an 'object' the only way?


Last is already a supported Linq extension. You can use it with any IEnumerable.


Last is a supported Linq expression, but if you do want to write a generic extension method, this is the syntax you're looking for: Put the generic <T> on the method declaration, not on the class.

    public static T Last<T>(this List<T> MyList)
    {
        return MyList[MyList.Count - 1];
    }


In case this was more a general question, not particularly about Last():

As long as the compiler is able to figure out which type is used, you can have generic type parameters on your method. When it can't infer them, you would have to specifiy them yourself. (See the methods Enumerable.OfType or Cast for details)

Here's an abstract example trying to show what is possible:

public static TResult Sample<TItem, TResult>(this IEnumerable<TItem> items, Func<TItem, TResult> gimmeThatValue)
{
  var firstItem = items.First();
  return gimmeThatValue(firstItem);
}

var items = new []{new{Value1 = 1, Value2 = "Abc"}};
int    value1 = items.Sample(i => i.Value1);
String value2 = items.Sample(i => i.Value2.Substring(2, 1));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号