c# - c# 以更简单的方式使用类属性作为参数
问题描述
我有一个方法可以使用类属性作为参数来获取列表的索引。
编码:
public static int GetIndex<T, TKey>(this T myTypeClass, Expression<Func<T, TKey>> propertySelector)
{
var body = (MemberExpression)propertySelector.Body;
var propertyInfo = (PropertyInfo)body.Member;
// list where I need to find the index for the property defined in the argument
List<KeyValuePair<PropertyInfo, int>> indexList = GlobalClassList;
// simple LINQ line to retrieve the int that corresponds with the 'propertyInfo'
int i = indexList.FindIndex(p => p.Key.Equals(propertyInfo));
return i;
}
调用方法:
MyClass myClass = new MyClass();
myClass.GetIndex(c=>c.property)
我正在尝试做的是仅使用类 ( c.property
) 的属性来简化方法中的参数,而不必依赖于Expression<Func<T, TKey>>
( c=>c.property
) 的使用。这可能吗?
解决方案
推荐阅读
- hololens - MRTK - 在运行时更改空间意识材料
- filesystems - Databricks 文件系统 - %sh ls 与 %fs ls
- java - 如何防止JPA查询相关实体
- c - strncat 导致缓冲区溢出
- reactjs - 如何在firestore中同时完全删除集合文档和子集合文档
- flutter - #_currentArena 是什么?(句法)
- http - 通过 HTTP 集成从 AWS Api Gateway 中的 websocket 提取 websocket 连接 ID 和其他详细信息
- sql - 将特定列从一个表复制到另一个
- android - 用房间库中的另一个实体列填充忽略的列
- python - 使用 Getter 和 Setter 装饰器时出现 RecursionError