在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 answersI 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 } }更多推荐
发布评论