[英]C# error casting an object to a generic interface
I have the following code. 我有以下代码。 I am unable to cast the object of ISearchProvider to another interface which the class has implemented. 我无法将ISearchProvider的对象强制转换为该类已实现的另一个接口。
public interface IGenericSearchProcessor<T> where T: ISearchCriteria
{
Task<ISearchResponse> Search(T criteria);
}
public class GibsonSearchProvider : IGenericSearchProcessor<ISearchCriteria>, IAggregateSearch, ISearchProvider
{
public async Task<ISearchResponse> Search(ISearchCriteria criteria)
{
return new BasicSearchResponse
{
AggregateResults = aggregates
};
}
}
public class GenericSearchStrategy<T> : ISearchStrategy<T> where T : ISearchCriteria
{
public Task<ISearchResponse> Search(ISearchProvider provider, T criteria)
{
//exception here when try to cast.
var p = (IGenericSearchProcessor<T>)provider;
//return ((IGenericSearchProcessor<T>)provider).Search(criteria);
}
}
That cast would only work if: 该转换仅在以下情况下有效:
Search
method is of a type that implements IGenericSearchProcessor<T>
and, 传递给您的Search
方法的对象属于实现IGenericSearchProcessor<T>
的类型,并且 IGenericSearchProcessor<T>
implements ISearchProvider
. IGenericSearchProcessor<T>
实现ISearchProvider
。 Your code shows that IGenericSearchProcessor<T>
implements ISearchCriteria
, not ISearchProvider
. 您的代码显示IGenericSearchProcessor<T>
实现ISearchCriteria
,而不是ISearchProvider
。 If you are just going to cast the parameter to IGenericSearchProcessor<T>
, then I would suggest just making that the type of the parameter: 如果您只是将参数转换为IGenericSearchProcessor<T>
,那么我建议您仅设置参数的类型:
public Task<ISearchResponse> Search(IGenericSearchProcessor<T> provider, T criteria) {
...
}
Just doing that will likely show where your other code could be going wrong. 这样做可能会显示其他代码可能在哪里出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.