gpt4 book ai didi

c# - 处理通用接口(interface)时的解决方法

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:50 24 4
gpt4 key购买 nike

我有以下界面:

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

如你所见,泛型类型参数只能是一个Translation类型或 child 。

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

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

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

entity is ITranslatable<Translation>行不通,因为 ITranslatable<Translation>不同于ITranslatable<TranslationImpl> , 即使 TranslationImpl Translation 扩展 .

我想到的另一件事是执行以下操作:

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

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

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

郑重声明,我真的需要子类中的属性为Collection<TranslationImpl>而不是 Collection<Translation> ,因为 EntityFramework 不支持抽象类映射。

PS:我真的不需要使用ICollection<TranslationImpl>对于上面的应用程序代码片段,访问 ICollection<Translation>就足够了。

有什么想法吗?

最佳答案

您无法使用 is 运算符确定一个类型是否实现了一个开放的通用接口(interface),但您可以使用反射来做到这一点”

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

关于c# - 处理通用接口(interface)时的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27315570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com