与调用正确的派生类型的通用方法 [英] Calling a generic method with the correct derived type

查看:90
本文介绍了与调用正确的派生类型的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情形:

我有三个班,我们姑且称之为 A B C 。所有他们的共同点是,他们来自同一个接口继承, ISomeInterface ,他们是映射到使用实体框架的实体类。

I have three classes, let's call them A, B and C. All they have in common is that they inherit from the same interface, ISomeInterface and that they are classes that are mapped to entities using Entity Framework.

我有收到一个实现此接口的对象列表的方法,但对象本身会实例 A C

I have a method that received a List of objects that implements this interface, but the objects themselves will be instances of A, B or C.

该方法外壳看起来像这样

The method shell looks like this

public void MyMethod(List<ISomeInterface> entityList)
{
  foreach(var entity in entityList)
  {
    ProcessEntity(entity);
  }
}

现在的问题是与 ProcessEntity 方法。这是一个通用的方法,需要根据类型或实体从数据库中检索匹配的元素的表,所以它看起来是这样的:

Now, the problem is with the ProcessEntity method. This is a generic method, that needs to retrieve the table of matching elements from the database according to the type or entity, so it looks like this:

public void ProcessEntity<T>(T entity)
{
  using( var repository = new DbRepository())
  {
    var set = repository.Set<T>();
    ...
  }
}



问题在于行 VAR集= repository.Set< T>(); 失败,因为 T ISomeInterface 在这种情况下,而不是实际的类型( A B 或<$ ç$ C> C ),所以它给出了一个例外,那就是无法与给定类型,这是可以理解的。

The problem is that the line var set = repository.Set<T>(); fails because T is ISomeInterface in this case, and not the actual type( A, B or C), so it gives an exception that is can't relate to the type given, which is understandable.

所以,我的问题是:我怎么能说ProcessEntity与实际类型列表内的对象,而不是interfacetype他们实现

So my question is: How can i call ProcessEntity with the actual type of the object inside the list, and not the interfacetype that they implements.

推荐答案

您可以使用通过实体ProcessEntity时动态关键字。在这种情况下实体的实际类型会在运行时确定

You can apply dynamic keyword when passing entity to ProcessEntity. In this case actual type of entity will be determined at runtime.

public void MyMethod(List<ISomeInterface> entityList)
{
  foreach(var entity in entityList)
  {
    dynamic obj = entity;
    ProcessEntity(obj);
  }
}

这篇关于与调用正确的派生类型的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆