【发布时间】:2020-07-25 11:43:55
【问题描述】:
在比较类型时,我试图选择正确的方法从容器中选择对象。 在下面的示例中,有 2 个接口:ISomeInterface、ISomeSubInterface,其中 ISomeSubInterface 继承自 ISomeInterface
还有2个类:InterfaceClass、SubInterfaceClass,其中名称表示继承的接口。
很快: InterfaceClassis ISomeInterface
SubInterfaceClass 是 ISomeSubInterface 是 ISomeInterface
在 IsOfType 方法中,我检查匹配的对象。
当前状态: 该方法检查容器中的对象是否属于声明的类型。当调用具有 ISomeInterface 泛型类型的方法时,如果容器中存在这两个类,则它们都匹配,因为它们都“是”ISomeInterface。
通缉状态: 该方法将返回与 ISomeInterface 具有最接近继承关系的对象。
随着容器保存对象,并且正在比较运行时类型,我明白为什么我当前的实现失败了。 我的问题是,是否有可能实施这种返回通缉状态的机制? 我不排除更改数据结构或将对象添加到该数据结构的方式。
class Program
{
static void Main(string[] args)
{
_ = new Test();
}
}
public class Test
{
private readonly List<ISomeInterface> _objects = new List<ISomeInterface>();
public Test()
{
ISomeInterface obj1 = new InterfaceClass();
ISomeInterface obj2 = new SubInterfaceClass();
_objects.Add(obj1);
_objects.Add(obj2);
IEnumerable<ISomeSubInterface> retObjs1 = Get<ISomeSubInterface>();
int count1 = retObjs1.Count(); // 1 As expected
IEnumerable<ISomeInterface> retObjs2 = Get<ISomeInterface>();
int count2 = retObjs2.Count(); // 2, wanted 1
}
private IEnumerable<T> Get<T>()
where T : ISomeInterface
{
return _objects.Where(IsOfType<T>).Cast<T>();
}
private bool IsOfType<T>(ISomeInterface obj)
where T : ISomeInterface
{
return typeof(T).IsAssignableFrom(obj.GetType());
}
}
internal class SubInterfaceClass: ISomeSubInterface { }
internal class InterfaceClass: ISomeInterface { }
internal interface ISomeSubInterface : ISomeInterface { }
internal interface ISomeInterface { }
不胜感激这方面的帮助。 谢谢。
【问题讨论】:
-
您的代码无法编译,顺便说一句。
-
谢谢,已编辑..
-
这样更好。这是微不足道的,但很高兴这些东西只是复制、粘贴和运行。 :-)
-
@haim770 - 接近重复,但不完全一致。该问题显示了如何构建一个查询来回答这个问题,但它不是一回事。
标签: c# generics inheritance types