使用表达式/lambda 设置属性值的通用方法
我正在尝试找到一种通用方法来为 lambda 表达式指定的属性赋值,请查看下面的示例代码,ConverToEntities 方法的签名将如何显示以及如何调用它?
static void Main()
{
List<long> ids = new List<long> {1, 2, 3};
//Non generic way
List<Data> dataItems = ids.ConvertToDataItems();
//Generic attempt!!
List<Data> differntDataItems =
ids.ConvertToEntities<Data>( p => p.DataId );
}
public class Data
{
public long DataId;
public string Name;
}
public static class ExtensionMethods
{
public static List<Data> ConvertToDataItems(this List<long> dataIds)
{
return dataIds.Select(p => new Data { DataId = p }).ToList();
}
public static List<T> ConvertToEntities<TProp>(
this List<long> entities, Func<TProp> lambdaProperty )
{
return entities.Select(p => new T {lambdaProperty} ).ToList();
}
}
I am trying to find a generic way to assign values to a property dictated by a lambda expression, look at the example code below, how would the signature for the ConverToEntities method look and how would it be called?
static void Main()
{
List<long> ids = new List<long> {1, 2, 3};
//Non generic way
List<Data> dataItems = ids.ConvertToDataItems();
//Generic attempt!!
List<Data> differntDataItems =
ids.ConvertToEntities<Data>( p => p.DataId );
}
public class Data
{
public long DataId;
public string Name;
}
public static class ExtensionMethods
{
public static List<Data> ConvertToDataItems(this List<long> dataIds)
{
return dataIds.Select(p => new Data { DataId = p }).ToList();
}
public static List<T> ConvertToEntities<TProp>(
this List<long> entities, Func<TProp> lambdaProperty )
{
return entities.Select(p => new T {lambdaProperty} ).ToList();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的。我能得到的最接近的是:
这有效。
我觉得你对你真正想要的返回类型有点困惑。如果能够在方法调用中指定我们想要的内容,那就太酷了。例如:
这为我们在返回类型上提供了更大的灵活性。但由于我们使用扩展来做到这一点,我认为这是不切实际的,因为我们需要知道我们要扩展什么类型:
好问题。
编辑代码建议修复。
Ok. The closest I could get was this :
This works.
I have the feeling you got urself a little confused with what you actually want as the return type. It would be cool to be able to specify what we want in the method call or smth. For example:
This provides us more flexibility on the return type. But since we are doing this using extensions, I assume this is impractical because we need to know what type we are extending:
Nice question.
EDIT Code suggestion fix.
你可以做这样的事情,但它并不那么简单或好。 lambda
p => p.DataId
为您提供属性的 get 访问器。您可以使用Expression
来获取setter,但最好直接在lambda中使用setter:实现如下所示:
You can do something like this, but it's not as simple or nice. The lambda
p => p.DataId
gives you the get accessor of the property. You could useExpression
s to get the setter, but it's probably better to use the setter directly in the lambda:The implementation would look like this:
我相信@Zortkun 关于返回类型的说法是正确的。尝试以下操作:
您将按如下方式调用它:
I believe @Zortkun is right about the return type. Try the followin:
and you would call it as follows: