想要使Func <UnknownType,bool>其中UnknownType仅在运行时已知

因此,我正在尝试使用atm表达式。得到以下代码:除以下几点外,代码工作正常:我需要用ForeignKeyProperty.PropertyType替换ViewModel类型,该类仅在运行时在var condition = Expression.Lambda < Func < ViewModel, bool> >


预期的最终结果:


ForeignKeyProperty.SetValue(model, repository.GetList  <ForeignKeyProperty.PropertyType >().Single(x => x.Id == model.Id));


protected List < Action < IVenturaRepository, ViewModel>> SetForeignKeyProperties<ViewModel>() where ViewModel : BaseViewModel

        {

            var viewModelType = typeof(ViewModel);

            var foreignKeyProperties = viewModelType.GetProperties().Where(x => x.PropertyType.IsSubclassOf(typeof(BaseViewModel)));

            var actions = new List < Action < IVenturaRepository, ViewModel>>();

            var repositoryType = typeof(IVenturaRepository);

            foreach(var ForeignKeyProperty in foreignKeyProperties)

            {

                var foreignKeyIdProperty = viewModelType.GetProperties().SingleOrDefault(x => x.Name == ForeignKeyProperty.Name + "Id");

                //ForeignKeyProperty.SetValue(model, repository.GetList<ViewModel>().Single(x => x.Id == model.Id));

                var listMethod = repositoryType.GetMethods().SingleOrDefault(x => x.Name == "GetList").MakeGenericMethod(ForeignKeyProperty.PropertyType);

                //Expression.Call(singleMethod,);

                var repositoryVariable = Expression.Parameter(repositoryType, "repository");

                var paramViewModelType = Expression.Parameter(viewModelType, "model");

                var paramForeignEntityId = Expression.Property(paramViewModelType, "Id");

                var listMethodCall = Expression.Call(repositoryVariable, listMethod);

                var modelParameter = Expression.Parameter(ForeignKeyProperty.PropertyType, "x");

                var foreignKeyTypeConstant = Expression.Constant(ForeignKeyProperty.PropertyType);

                       ),

                        modelParameter

                    );

            }

            return actions;

        }

有人可以指出我正确的方向吗?


素胚勾勒不出你
浏览 124回答 2
2回答

叮当猫咪

使用Object作为类型。那么您可以在运行时以及在将类型强制转换为正确类型之后通过getType()检查类型。或使用动态以避免投射。
打开App,查看更多内容
随时随地看视频慕课网APP