0

我想要获得的是来自实体的属性并对值求和。我正在使用泛型,实体的类型和属性的名称在运行时是已知的。以下(简化)代码编译良好,但抛出“对象与目标类型不匹配”。尝试从实体获取属性时。这是代码:

    public class SomeModel
    {
        public int ValueA { get; set; }
        public int ValueB { get; set; }
    }

    public class SomeViewModel
    {
        public int ViewValue { get; set; }
    }

    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            IEnumerable<SomeModel> data = GetData();

            var result = SumValues(data, a => new SomeViewModel { ViewValue = a.ValueA });

            return Content(string.Format("Total is: {0}", result));
        }

        private int SumValues<T, TRes>(IEnumerable<T> data, Func<T, TRes> transformation)
        {
            var transformedData = data.Select(transformation);
            Type type = typeof(TRes);
            PropertyInfo property = type.GetProperty("ViewValue");
            IEnumerable<int> listOfValues = property.GetValue(transformedData, null) as IEnumerable<int>;
            var sum = listOfValues.Sum();

            return sum;
        }

        private IEnumerable<SomeModel> GetData()
        {
            var data = new List<SomeModel>();
            Random random;
            for (int i = 0; i < 1000; i++)
            {
                random = new Random(i);
                data.Add(new SomeModel { ValueA = random.Next(5,100), ValueB = random.Next(20,80) });
            }
            return data;
        }
    }

我在这里生成假数据,但真正的应用程序是使用 EF 从数据库中获取数据。泛型对我来说是新的,所以请任何指出我正确方向的建议将不胜感激。

4

1 回答 1

0

在这一行:

IEnumerable<int> listOfValues = 
                       property.GetValue(transformedData, null) as IEnumerable<int>;

您正在尝试检索对象的ViewValue属性值List<SomeModel>,但List<SomeModel>没有ViewValue属性。你可以做的一件事是:

IEnumerable<int> listOfValues = 
                       transformedData.Select(i => (int)property.GetValue(i, null));

但更清洁的解决方案是完全避免反射,因为这里不需要它:

interface IViewValue
{
    int ViewValue { get; set; }
}

public class SomeViewModel : IViewValue
{
    public int ViewValue { get; set; }
}

private int SumValues<T, TRes>(IEnumerable<T> data, Func<T, TRes> transformation)
                                            where TRes : IViewValue
{
    var transformedData = data.Select(transformation);
    IEnumerable<int> listOfValues = transformedData.Select(i => i.ViewValue);
    var sum = listOfValues.Sum();

    return sum;
}
于 2013-03-14T14:26:03.810 回答