在lambda表达式中使用string作为属性c#[duplicate](Use string as a property in lambda expression c# [duplicate])

编程入门 行业动态 更新时间:2024-10-24 18:25:25
在lambda表达式中使用string作为属性c#[duplicate](Use string as a property in lambda expression c# [duplicate])

这个问题在这里已有答案:

使用C# 21答案中的 反射从字符串中获取属性值

我有一个方法,我传递字符串和列表。 我想要实现的是将字符串转换为lambda表达式属性。

private someMethod(string myTypeString, List<Values> typeList) { foreach(var type in typeList.Where(x => x."myTypeString" > DateTime.Now)) { //do my loop } }

有没有办法做到这一点?

This question already has an answer here:

Get property value from string using reflection in C# 22 answers

I have a method which I pass string and a list in to. What I'm trying to achieve is to convert the string into lambda expression property.

private someMethod(string myTypeString, List<Values> typeList) { foreach(var type in typeList.Where(x => x."myTypeString" > DateTime.Now)) { //do my loop } }

Is there a way to do that?

最满意答案

您可以尝试使用Reflection

using System.Reflection; ... private void someMethod(string myTypeString, List<Values> typeList) { PropertyInfo pi = typeof(Values) .GetProperty(myTypeString, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | // private/internal/protected System.Reflection.BindingFlags.Public); // property exists, can be read and returns DateTime if (null == pi) return; // or throw exception else if (!pi.CanRead) return; // or throw exception else if (pi.PropertyType != typeof(DateTime)) return; // or throw exception foreach(var type in typeList .Where(x => (DateTime) (pi.GetValue(x, null)) > DateTime.Now)) { //do my loop } }

You can try using Reflection:

using System.Reflection; ... private void someMethod(string myTypeString, List<Values> typeList) { PropertyInfo pi = typeof(Values) .GetProperty(myTypeString, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | // private/internal/protected System.Reflection.BindingFlags.Public); // property exists, can be read and returns DateTime if (null == pi) return; // or throw exception else if (!pi.CanRead) return; // or throw exception else if (pi.PropertyType != typeof(DateTime)) return; // or throw exception foreach(var type in typeList .Where(x => (DateTime) (pi.GetValue(x, null)) > DateTime.Now)) { //do my loop } }

更多推荐

本文发布于:2023-08-05 05:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1427552.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   属性   string   lambda   property

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!