传递属性本身作为C#中的参数

时间:2012-06-24 15:54:34

标签: c# properties parameter-passing

我正在寻找一种将属性本身传递给函数的方法。不是财产的价值。函数事先不知道哪个属性将用于排序。此示例中最简单的方法是:使用不同的参数类型创建4个覆盖。其他方法是使用typeof()内部函数。当Class1具有数百个属性时,这两种方式都是不可接受的。到目前为止,我发现了以下方法:

class Class1
{
    string vehName;
    int maxSpeed;
    int fuelCapacity;
    bool isFlying;
}

class Processor
{
    List<Class1> vehicles = null;
    Processor(List<Class1> input)
    {
        vehicles = input;
    }

    List<Class1> sortBy(List<Class1> toSort, string propName)
    {
        if (toSort != null && toSort.Count > 0)
        {
            return toSort.OrderBy(x => typeof(Class1).GetProperty(propName).GetValue(x, null)).ToList();
        }
        else return null;
    }
}

class OuterUser
{
    List<Class1> vehicles = new List<Class1>();
    // ... fill the list
    Processor pr = new Processor(vehicles);
    List<Class1> sorted = pr.sortBy("maxSpeed");
}

我不喜欢这种方法,因为在将字符串传递给处理函数时存在“人为错误”的风险。当字符串由代码的其他部分生成时,这将变得更加丑陋。 请提出更优雅的方法来实现Class1属性的传递以进行进一步处理。使用恕我直言的最佳选择(或类似的东西):

vehicles = sortBy(vehicles, Class1.maxSpeed);

7 个答案:

答案 0 :(得分:57)

您可以将属性访问器传递给方法。

List<Class1> SortBy(List<Class1> toSort, Func<Class1, IComparable> getProp)
{
    if (toSort != null && toSort.Count > 0) {
        return toSort
            .OrderBy(x => getProp(x))
            .ToList();
    }
    return null;
}

你会这样称呼:

var result = SortBy(toSort, x => x.maxSpeed);

但是你可以更进一步,编写自己的扩展方法。

public static class CollectionExtensions
{
    public static List<TSource> OrderByAsListOrNull<TSource, TKey>(
        this ICollection<TSource> collection, Func<TSource,TKey> keySelector)

        if (collection != null && collection.Count > 0) {
            return collection
                .OrderBy(x => keySelector(x))
                .ToList();
        }
        return null;
    }
}

现在你可以像这样排序

List<Class1> sorted = toSort.OrderByAsListOrNull(x => x.maxSpeed);

但也

Person[] people = ...;
List<Person> sortedPeople = people.OrderByAsListOrNull(p => p.LastName);

请注意,我将第一个参数声明为ICollection<T>,因为它必须满足两个条件:

  1. 必须具有Count属性
  2. 为了能够应用LINQ方法IEnumerable<T>,它必须是OrderBy
  3. List<Class1>是一个ICollection<T>,也是一个数组Person[]和其他许多集合一样。


    到目前为止,我已经展示了如何阅读房产。如果方法需要设置属性,则还需要传递一个setter委托

    void ReadAndWriteProperty(Func<Class1, T> getProp, Action<Class1, T> setProp)
    

    T是属性的类型。

答案 1 :(得分:26)

您可以使用lambda表达式传递属性信息:

void DoSomething<T>(Expression<Func<T>> property)
{
    var propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
    if (propertyInfo == null)
    {
        throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
    }
}

用法:

DoSomething(() => this.MyProperty);

答案 2 :(得分:5)

我发现@ MatthiasG的答案中缺少的是如何获取属性值而不仅仅是它的名称。

public static string Meth<T>(Expression<Func<T>> expression)
{
    var name = ((MemberExpression)expression.Body).Member.Name;
    var value = expression.Compile()();
    return string.Format("{0} - {1}", name, value);
}

使用:

Meth(() => YourObject.Property);

答案 3 :(得分:4)

这里有很好的解决方案......

Passing properties by reference in C#

void GetString<T>(string input, T target, Expression<Func<T, string>> outExpr)
{
    if (!string.IsNullOrEmpty(input))
    {
        var expr = (MemberExpression) outExpr.Body;
        var prop = (PropertyInfo) expr.Member;
        prop.SetValue(target, input, null);
    }
}

void Main()
{
    var person = new Person();
    GetString("test", person, x => x.Name);
    Debug.Assert(person.Name == "test");
}

答案 4 :(得分:3)

为什么不使用Linq呢?像:

vehicles.OrderBy(v => v.maxSpeed).ToList();

答案 5 :(得分:0)

只是从上面的答案中添加。您也可以为订单方向做一个简单的标记。

public class Processor
{
    public List<SortableItem> SortableItems { get; set; }

    public Processor()
    {
        SortableItems = new List<SortableItem>();
        SortableItems.Add(new SortableItem { PropA = "b" });
        SortableItems.Add(new SortableItem { PropA = "a" });
        SortableItems.Add(new SortableItem { PropA = "c" });
    }

    public void SortItems(Func<SortableItem, IComparable> keySelector, bool isAscending)
    {
        if(isAscending)
            SortableItems = SortableItems.OrderBy(keySelector).ToList();
        else
            SortableItems = SortableItems.OrderByDescending(keySelector).ToList();
    }
}

答案 6 :(得分:0)

我想给出一个简单易懂的答案。

函数的参数是这样的:System.Func<class, type of the property>

然后我们像下面这样传递属性:Function(x => x.Property);

代码如下:

class HDNData
{
    private int m_myInt;
    
    public int MyInt
    {
        get { return m_myInt; }
    }
    
    public void ChangeHDNData()
    {
        if (m_myInt == 0)
            m_myInt = 69;
        else
            m_myInt = 0;
    }
}

static class HDNTest
{
    private static HDNData m_data = new HDNData();
    
    public static void ChangeHDNData()
    {
        m_data.ChangeHDNData();
    }
    
    public static void HDNPrint(System.Func<HDNData, int> dataProperty)
    {
        Console.WriteLine(dataProperty(m_data));//Print to console the dataProperty (type int) of m_data
    }
}

//******Usage******
HDNTest.ChangeHDNData();
//This is what you want: Pass property itself (which is MyInt) to function as parameter in C#
HDNTest.HDNPrint(x => x.MyInt);