是否有可能從方法返回一個通用的Func? 我想要做的就像下面的GetSortFunc。方法返回通用函數c#
public class Example
{
private List<MyObject> _objects;
public Example()
{
_objects = new List<MyObject>
{
new MyObject {Id = 1, Name = "First", Value = 100.0},
new MyObject {Id = 2, Name = "Second", Value = 49.99},
new MyObject {Id = 3, Name = "Third", Value = 149.99}
};
}
public void Sort(SomeEnum sortOptions)
{
_objects = _objects.OrderBy(GetSortFunc(sortOptions));
}
private Func<MyObject, TKey> GetSortFunc(SomeEnum sortOptions)
{
switch (sortOptions)
{
case SomeEnum.First:
return x => x.Id;
case SomeEnum.Second:
return x => x.Name;
case SomeEnum.Third:
return x => x.Value;
}
}
}
的SomeEnum和myObject的是這樣的:
public enum SomeEnum
{
First,
Second,
Third
}
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
public double Value { get; set; }
}
這是可以做到的還是我在錯誤的軌道上?
是的有可能:-) – Grundy
看起來它會少了很多的工作,你只使用'.OrderBy()',因爲它是 – Alex
首先,這是可能的,其次,是否可能,你可以編譯你的代碼並找出答案。 –