简体   繁体   English

通过反射C#在参数中使用参数调用方法

[英]call method with params in arguments through reflection c#

Method return record from Database. 来自数据库的方法返回记录。

    public T Find(params object[] primaryKeys)
    {
        var dbSet = _sessionContext.Set<T>() as DbSet<T>;

        return dbSet != null ? dbSet.Find(primaryKeys) : null;
    }

I'm trying to call in through reflection 我试图通过反思来呼唤

var methodCreateReadRepositoryEntity = 
     typeof(IRepositoryFactory)
    .GetMethod("CreateReadRepository")
    .MakeGenericMethod(entityMetadata.GetEntityType());

var entityReadRepository = 
     methodCreateReadRepositoryEntity
    .Invoke(_repositoryFactory, new object[] { _sessionMarketContext });

List<object> keys = new List<object>();

keys.Add(value);

var methodEntityGet = 
    entityReadRepository.GetType().GetMethod("Find", new Type[] { typeof(object[])});

var fromRepo = 
    methodEntityGet.Invoke(entityReadRepository, new object[]{new []{ keys.ToArray()[0]}});

value is Guid. 值是Guid。 And I have error 我有错误

The type of one of the primary key values did not match the type defined in the entity. 主键值之一的类型与实体中定义的类型不匹配。 Exception has been thrown by the target of an invocation. 调用的目标已引发异常。

Your last line should be as follows. 您的最后一行应如下所示。 You need to be explicit with the array type, and there is no need to create a List . 您需要明确使用数组类型,并且无需创建List

var fromRepo = 
    methodEntityGet.Invoke(entityReadRepository, new object[]{new object []{value}});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM