在C#中,如果我的对象支持该接口,我该如何检查T是否为IInterface类型并将其转换为该类型? [英] In C# how can i check if T is of type IInterface and cast to that if my object supports that interface?
问题描述
泛型
传入 T
,我想运行一个检查到看看 T
是一个实现接口
的对象
和如果是这样,请调用接口
中方法之一
。 我不想让 T
约束仅限于该类型。是否有可能做到这一点?
例如:
public class MyModel< T> :IModel< T>其中T:MyObjectBase
{
public IQueryable< T> GetRecords()
{
var entities = Repository.Query< T>();
if(typeof(IFilterable).IsAssignableFrom(typeof(T)))
{
// Filterme是一种接受IEnumerable< IFilterable>
entities = FilterMe(entities));
}
返回实体;
}
public IEnumerable< TResult> FilterMe< TResult>(IEnumerable< TResult> linked)其中TResult:IFilterable
{
var dict = GetDict();
return linked.Where(r => dict.ContainsKey(r.Id));
我得到的错误是:
错误21类型'TResult'不能用作泛型类型或方法'FilterMe(System.Collections.Generic.IEnumerable)'中的类型参数'TResult'。不存在从'TResult'到'IFilterable'的隐式引用转换。
c $ c> Cast <>():
if(typeof(IFilterable).IsAssignableFrom (typeof(T))){
entities = FilterMe(entities.Cast< IFilterable>())。AsQueryable()。Cast< T>();
请注意,使用 Cast <>
将实体列表转换为正确的子类型。除非 T
实现 IFilterable
,否则这个转换将失败,但由于我们已经检查过,所以我们知道它会。 p>
In C#, I have a function that passes in T
using generics
and I want to run a check to see if T
is an object
that implements a interface
and if so call one of the methods
on that interface
.
I don't want to have T
constraints to only be of that Type. Is it possible to do this?
For example:
public class MyModel<T> : IModel<T> where T : MyObjectBase
{
public IQueryable<T> GetRecords()
{
var entities = Repository.Query<T>();
if (typeof(IFilterable).IsAssignableFrom(typeof(T)))
{
//Filterme is a method that takes in IEnumerable<IFilterable>
entities = FilterMe(entities));
}
return entities;
}
public IEnumerable<TResult> FilterMe<TResult>(IEnumerable<TResult> linked) where TResult : IFilterable
{
var dict = GetDict();
return linked.Where(r => dict.ContainsKey(r.Id));
}
}
The error that I am getting is:
Error 21 The type 'TResult' cannot be used as type parameter 'TResult' in the generic type or method 'FilterMe(System.Collections.Generic.IEnumerable)'. There is no implicit reference conversion from 'TResult' to 'IFilterable'.
The missing piece is Cast<>()
:
if(typeof(IFilterable).IsAssignableFrom(typeof(T))) {
entities = FilterMe(entities.Cast<IFilterable>()).AsQueryable().Cast<T>();
}
Note the use of Cast<>()
to convert the entities list to the correct subtype. This cast would fail unless T
implements IFilterable
, but since we already checked that, we know that it will.
这篇关于在C#中,如果我的对象支持该接口,我该如何检查T是否为IInterface类型并将其转换为该类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!