使用反射来检索列表中的值 [英] Using reflection to retrieve a value from a list

查看:181
本文介绍了使用反射来检索列表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个蓝色的移动服务检索表的简单方法。

I have a simple method which retrieves a table from an azure mobile service.

public static async List<T>GetDataFromListTable<T>()
{
    var data = await MobileService.GetTable<T>().ToListAsync();
    return data.Count != 0 ? data : null;
}

这工作得很好。

我所试图做的是有另一个需要被从服务返回,并返回该参数值的参数名的方法。到目前为止,我有这个

What I am trying to do is have another method that takes a parameter name which is returned from the service and return the value of that parameter. So far I have this

public static async Task<T> GetDataFromTable<T>(string paramName)
    {
        var k = Activator.CreateInstance(typeof(T));
        var members = typeof(T).GetProperties().Select(t=>t.Name).ToList();
        if (!members.Contains(paramName))
            return (T)k;
        var mn = typeof(T).GetProperties()[members.IndexOf(paramName)];
        var data = GetDataFromListTable<T>();
        var retval = data.Select(t => t.mn);
    }

问题显然是我不能做LINQ查询为T不包含MN。我也不能使用

The issue is obviously that I can't do the Linq query as T doesn't contain mn. I can also not use

var retval = data.Select(t=>t.paramName);

作为PARAMNAME是只是一个字符串再一类中的一个成员presentation。

as paramname is a just a string representation of a member within a class.

在简单地说...

1的方法具有参数名称,从方法2抓起列表从方法2返回的列表中,找到参数名称和返回关联值。

method 1 has the parameter name, grabs a list from method 2. From the returned list in method 2, find the parameter name and return the associated value.

有没有办法做我想要做什么?

Is there a way to do what I'm trying to do?

推荐答案

您可以这样做:

var retval = data.Select(t => mn.GetGetMethod().Invoke(t, null));

var retval = data.Select(t => mn.GetValue(t, null));


您还可以简化您的code像这样(没有测试,不好意思):


You can also simplify your code with something like this (not tested, sorry):

public static async Task<T> GetDataFromTable<T>(string paramName)
{
    var k = Activator.CreateInstance(typeof(T));
    var mn = typeof(T).GetProperty(paramName);

    if (mn == null)
        return (T)k;

    var data = GetDataFromListTable<T>();
    var retval = data.Select(t => mn.GetGetMethod().Invoke(t, null));

    ...
}

这篇关于使用反射来检索列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆