【问题标题】:Is there a way to find an interface implementation based on a generic type argument?有没有办法找到基于泛型类型参数的接口实现?
【发布时间】:2009-11-05 17:52:29
【问题描述】:

我有一个数据访问库,它有几个类都实现了相同的接口,并且有一个泛型类型参数:

public interface IGetByCommonStringRepository<TEntity>
{
    TEntity GetByCommonStringColumn(string commonString);
}

public class Repository1<Entity1> : IGetByCommonStringRepository<Entity1>
{
    public Entity1 GetByCommonStringColumn(string commonString)
    {
        //do stuff to get the entity
    }
}

public class Repository2<Entity2> : IGetByCommonStringRepository<Entity2>
//...and so on 

与其强迫这个库的使用者为每个&lt;TEntity&gt; 分别实例化四个存储库类之一,我希望有某种方法可以在同一个“帮助程序/实用程序”类中创建一个静态方法程序集,它将能够辨别要实例化哪个实现、创建实例并执行GetByCommonStringColumn 方法。有点像...

public static TEntity GetEntityByCommonStringColumn(string commonString) where TEntity : class
{
    IGetByCommonStringRepository<TEntity> repository = 
        DoMagicalReflectionToFindClassImplementingIGetByCommonString(typeof(TEntity));
    //I know that there would have to an Activator.CreateInstance() 
    //or something here as well.
    return repository.GetByCommonStringColumn(commonString) as TEntity;
}

这样的事情可能吗?

【问题讨论】:

  • 示例代码中的类没有实现IGetByCommonStringRepository&lt;&gt;

标签: c# generics reflection interface


【解决方案1】:

该示例仍需要进一步修复。对于每个存储库,它都缺少一个约束。对于每个公共(现在它是无效的私有)方法,它也缺少一个函数体。对于该接口方法,它需要一个通用参数。

如果我理解正确,请尝试或玩弄:

public static TEntity clr_bloat_reflected_msdn_method<TEntity>(string commonString) where TEntity : class
        {
            Assembly a = Assembly.GetExecutingAssembly();
            foreach (Type t in a.GetTypes())
                if (!t.IsAbstract && typeof(IGetByCommonStringRepository<TEntity>).IsAssignableFrom(t))
                    return ((IGetByCommonStringRepository<TEntity>)Activator.CreateInstance(t)).GetByCommonStringColumn(commonString);
            return null;
        }

【讨论】:

  • 编辑原始帖子以修复代码。有时很难将 IDE 中的特定情境代码转换为 Markdown。
  • 首先是中断,然后我的键盘响了,然后 Windows 开始了通常的 7 天运行挂起并丢失图标、音频等,然后进入拼写。现在它是我在 stackoverflow.com @ ASP.NET MVC 上的代码格式。是时候去做认真的工作了,又要戒掉另一个瘾了……叹息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
相关资源
最近更新 更多