【问题标题】:Access properties of unknown type in IList<T>访问 IList<T> 中未知类型的属性
【发布时间】:2012-11-21 15:43:34
【问题描述】:

我正在实现一个自定义控件,它接收 T 类型的属性列表(作为字符串)和一个 IList 并将其呈现到 HTML 表中。我有标记和CreateChildControls 部分。

我想要做的是通过反射遍历属性并获取在列表上运行的foreach 循环内的属性值。

在编译时我不知道 T 是什么,我希望能够为任何 T 容纳 List。

最好的方法是什么?

编辑:

public class CustomControl : System.Web.UI.WebControls.WebControl, INamingContainer
{
    private List<string> _properties;
    private **?????????** _dataSource;

    public List<string> Properties
    { set { _properties = value; } }

    public **?????????** DataSource
    { set { _dataSource = value; } }
}

现在假设我将 Properties 的值设置为这样的:

_properties = new List<string>()
        {
            "FirstName",
            "LastName"
        };

并传入一个person类型的对象列表:

public class Person
{
    public string FirstName
    { get; set; }
    public string LastName
    { get; set; }
}

calss 只是一个占位符。我想对列表中的任何 T 执行此操作。 调用类知道类型 T 而自定义控件不知道。此外,自定义控件本身不打算成为一个泛型类。 希望这有助于集中我的问题。

【问题讨论】:

  • 好吧,你试过什么? (提示:typeof(T).GetProperty(...) 是你的朋友...)
  • @JonSkeet - List 的属性应该是什么类型?列表?我需要投吗?如果是,那是什么?
  • 我不知道 - 我们对上下文的了解不够。 (例如,这可以是泛型方法吗?还是泛型类型?调用者知道类型,还是应该是动态的?)
  • @JonSkeet - 我用代码示例和更好的解释更新了我的问题(我希望 :))谢谢!
  • foreach (var x in _dataSource) { x.GetType().GetProperty(...) } 不是您要的?

标签: c#-4.0 generics reflection


【解决方案1】:

您可以将数据源定义为普通的IEnumerable,然后通过反射获取每种类型的值。例如:

private IEnumerable _dataSource;

foreach (object o in _dataSource)
{
    foreach (string propName in _properties)
    {
        PropertyInfo prop = o.GetType().GetProperty(propName);

        // ...
    }
}

【讨论】:

    猜你喜欢
    • 2011-06-16
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2022-07-06
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多