C# 从对象获取通用列表(过度反射)

C# 从对象获取通用列表(过度反射),c#,reflection,C#,Reflection,我通过反射查询一些数据。返回的数据类型是System.data.datacolumn[](变量“test”)。我想将其转换为通用列表(例如字符串列表)。可能吗 public IEnumerable<string> GetStringList(string property) { var test = GetPropertyValue(SomeObject, property); // MAGIC // return test; } public obje

我通过反射查询一些数据。返回的数据类型是System.data.datacolumn[](变量“test”)。我想将其转换为通用列表(例如字符串列表)。可能吗

public IEnumerable<string> GetStringList(string property)
{
   var test =  GetPropertyValue(SomeObject, property);

    // MAGIC //

   return test;
}


public object GetPropertyValue(object obj, string propertyName)
{
    var propertyNames = propertyName.Split('.');

    foreach (var t in propertyNames)
    {
        if (obj != null)
        {
            var propertyInfo = obj.GetType().GetProperty(t);
            obj = propertyInfo != null ? propertyInfo.GetValue(obj) : null;
        }
    }

    return obj;
}
公共IEnumerable GetStringList(字符串属性) { var test=GetPropertyValue(SomeObject,property); //魔力// 回归试验; } 公共对象GetPropertyValue(对象obj,字符串propertyName) { var propertyNames=propertyName.Split('.'); foreach(propertyNames中的var t) { 如果(obj!=null) { var propertyInfo=obj.GetType().GetProperty(t); obj=propertyInfo!=null?propertyInfo.GetValue(obj):null; } } 返回obj; } 您可以试试这个

if (test is IEnumerable) {
    var values = test as IEnumerable;

    //Method 1: convert to list
    var asList = values.Cast<object>().ToList();

    //Method 2: iterate to IEnumerable and add to List
    var asList = new List<object>();
    foreach (var value in values)
    {
        asList.Add(value);
    }
}
if(测试是IEnumerable){
var值=测试为IEnumerable;
//方法1:转换为列表
var asList=values.Cast().ToList();
//方法2:迭代到IEnumerable并添加到列表
var asList=新列表();
foreach(值中的var值)
{
asList.Add(值);
}
}

这样做的结果应该是什么?
DataColumn
本身不包含任何有用的数据,可以保存为
.ColumnName
。如果您试图从
DataTable
中提取数据,可能有更好的方法。对于
IEnumerable
@canton7,没有
ToList()
方法,请尝试
values.Cast().ToList()