首页 > 解决方案 > 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) 的使用。这可能吗?

标签: c#reflection

解决方案


推荐阅读