【问题标题】:Workaround when dealing with generic interfaces处理通用接口时的解决方法
【发布时间】:2014-12-05 12:07:39
【问题描述】:

我有如下界面:

public interface ITranslatable<T> : IPersistableEntity where T : Translation {
    ICollection<T> Translations { get; set; }
}

如您所见,泛型类型参数只能是Translation 类型或子类型。

在我的应用程序的其他地方,我有以下代码:

foreach(E entity in entities) {
    if(entity is ITranslatable<?>)
      //Cast the entity and access the ICollection<?> property
}

正如您在 中看到的那样? 我不知道要传递什么作为类型参数。我不想像 E 那样通过泛型将特定类型传递给该类,因为我只在那里使用它并且我希望它是透明的。

entity is ITranslatable&lt;Translation&gt; 不起作用,因为 ITranslatable&lt;Translation&gt;ITranslatable&lt;TranslationImpl&gt; 不同,即使 TranslationImpl Translation 扩展

发生在我身上的另一件事是:

public interface ITranslatable : IPersistableEntity {
    ICollection<Translation> Translations { get; set; }
}

public interface ITranslatable<T> : ITranslatable where T : Translation {
    ICollection<T> Translations { get; set; }
}

但同样,在实现这个接口时,我最终得到了两个不同的属性,这是多余的和丑陋的。

仅作记录,我真的需要子类中的属性为Collection&lt;TranslationImpl&gt; 而不是Collection&lt;Translation&gt;,因为EntityFramework 不支持抽象类映射。

PS:对于上面的应用程序代码 sn-p,我真的不需要使用ICollection&lt;TranslationImpl&gt;,访问ICollection&lt;Translation&gt; 就足够了。

有什么想法吗?

【问题讨论】:

  • 使用附加接口方法,是不是实现ICollection&lt;Translation&gt; Translations 属性explicitly 不适合您?实现ITranslatable&lt;T&gt; 的对象将只有ICollection&lt;T&gt; Translations 属性(嗯,它们确实有,但它被隐藏了),而实现ITranslatable 的对象只有ICollection&lt;Translation&gt; Translations
  • @hantoun 不能让对象实现ICollection&lt;Translation&gt;,因为Translation 是一个抽象类,EF 为它哭泣。但是,我确实希望能够将实现转换为接口,在那里我可以将属性获取为ICollection&lt;Translation&gt;,即使在实现时它们是ICollection&lt;T&gt;

标签: c# entity-framework generics interface


【解决方案1】:

你不能确定一个类型是否使用is操作符实现了一个开放的通用接口,但你可以使用反射'

if(entity.GetType().GetInterfaces().Any(x =>
  x.IsGenericType &&
  x.GetGenericTypeDefinition() == typeof(ITranslatable<>)))

【讨论】:

  • 有趣的方法!会尝试并让你知道。 (顺便说一句,我如何在不知道类型参数的情况下将我的实体 cast 到接口?这是不可能的,对吧?我确实知道类型参数的 base class
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
  • 2023-03-28
  • 2010-12-16
  • 2017-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多