创建将在.net核心中返回泛型抽象类型对象的工厂



我正在创建使用抽象泛型类作为基础的代码。我有点卡住了,因为我试图创建一个工厂,它将根据插入的对象类型返回特定的对象。

比方说,我想和对象进行比较,以检查它们是否相等。在我的场景中,如果对象是IEnumerableIList类型,我想在此基础上比较对象

我的代码:

接口:

public interface IObjectComparer<in T>
{
bool Compare(T obj1, T obj2);
}

基本类别:

public abstract class ObjectComparerBase<T> : IObjectComparer<T>
{
public abstract bool Compare(T obj1, T obj2);
public void SomeUsefullHelperMethod()
{
}
}

IList对象比较器:

public sealed class ListObjectComparer : ObjectComparerBase<IList>
{
public override bool Compare(IList obj1, IList obj2)
{
throw new NotImplementedException();
}
}

IEnumerable对象比较器

public sealed class EnumerableObjectComparer : ObjectComparerBase<IEnumerable>
{ 
public override bool Compare(IEnumerable obj1, IEnumerable obj2)
{
throw new System.NotImplementedException();
}
}

最后,我有我的工厂,它应该决定我是否需要为特定对象使用哪个比较器:

public sealed class ComparerRetriever
{
public static IObjectComparer<T> Retrieve<T>(T obj)
{
IObjectComparer<T> comparer = null;
switch (typeof(T))
{
case IEnumerable o:
{
comparer = new EnumerableObjectComparer();
break;
}
case IList o:
{
comparer = new ListObjectComparer();
break;
}
default:
throw new NotSupportedException("Not Supported Type");
}
return comparer;
}
}

我的问题:

在当前的场景中,我不能使用我的ComparerRetriever类,因为compilator说ListObjectComparerEnumerableObjectComparer都不是IObjectComparer<T>类型。

我的问题是为什么?我的对象有ObjectComparerBase<T>类作为父类,并且这个类正在实现IObjectComparer<T>,所以在我看来EnumerableObjectComparerListObjectComparer应该是ObjectComparerBase<T>的类型

也许我错过了什么,但现在我看不清是什么。

你能帮我吗?

谢谢。

因此,这可以正常工作,并按预期返回类。您必须将IList放在第一位,因为IList实现了IEnumerable,如果IEnumeraable是第一位,那么它也将属于这种情况。

public sealed class ComparerRetriever
{
public static IObjectComparer<T> Retrieve<T>(T obj)
{
IObjectComparer<T> comparer;
switch (typeof(T))
{
case IList o:
{
comparer = new ListObjectComparer() as IObjectComparer<T>;
break;
}
case IEnumerable o:
{
comparer = new EnumerableObjectComparer() as IObjectComparer<T>;
break;
}

default:
throw new NotSupportedException("Not Supported Type");
}
return comparer;
}
}

不过,我确实认为,传递给Retrieve方法的任何对象都会遇到默认情况,因为它将具有具体类型,而typeof将导致该具体类型而不是Intreface

例如,当我进行测试时,我创建了

class SimpleList : IList
{
... blah
}

不出所料,typeof调用导致SimpleList而不是IList,因此它总是抛出

NotSupportedException("Not Supported Type");

很明显,我可能错了,你可能领先我一步,所以我会把我的答案留在那里,因为我相信我已经回答了最初的问题

更新经过更多的测试,我不确定你是否可以在接口上使用模式匹配,我已经将我的实现更改为下面的,我仍然使用默认情况。

public static IObjectComparer<T> Retrieve<T>(T obj)
{
IObjectComparer<T> comparer;
var interf = typeof(T).GetInterfaces().FirstOrDefault();
switch (interf)
{
case IList o:
{
comparer = new ListObjectComparer() as IObjectComparer<T>;
break;
}
case IEnumerable o:
{
comparer = new EnumerableObjectComparer() as IObjectComparer<T>;
break;
}

default:
throw new NotSupportedException("Not Supported Type");
}
return comparer;
}

最新更新