与调用接口实例泛型方法 [英] Calling a generic method with interface instances
问题描述
作为后续问题来这个
public interface IFeature { }
public class FeatureA : IFeature { }
IFeature a = new FeatureA();
Activate(a);
private static void Activate<TFeature>(TFeature featureDefinition) where TFeature : IFeature
{
}
我已了解,一旦 FeatureA
被强制转换为的iFeature
泛型方法总是会得到的iFeature
类型的参数。
I undestand, that once the FeatureA
is casted to IFeature
the generic method will always get IFeature
as type parameter.
我们有我们提供了一个服务列表功能(列表与LT; iFeature的>
)。如果我们要遍历这些功能,通过每个泛型方法,我想有没有办法让在泛型方法比
We have a service with provides us with a list features (List<IFeature>
). If we want to iterate over those features, passing each in the generic method, I guess there is no way to get the concrete type in the generic method other than
- $ B等具体类型$ b
- 使用反射
- 使用动态变量来确定在运行时类型(的与调用正确的派生类型一个泛型方法)
- using reflection
- using a dynamic variable to determine the type on runtime (Calling a generic method with the correct derived type)
由于反射是非常昂贵的,我想用动态转换。是否有任何缺点调用的方法呀?不知怎的,我这样做的时候觉得脏: - )
Since reflection is very costly, I would like to use the dynamic cast. Is there any downside to call the method that way? Somehow I feel dirty when doing that :-)
推荐答案
您可以使用访问者模式如下假设你可以修改你的代码库。否则,使用动态
You can use visitor pattern as follows assuming that you can modify your codebase. Otherwise, use dynamic.
public interface IFeature
{
void Accept(Visitior visitor);
}
public class FeatureA : IFeature
{
public void Accept(Visitior visitor)
{
visitor.Visit(this);
}
}
public class FeatureB : IFeature
{
public void Accept(Visitior visitor)
{
visitor.Visit(this);
}
}
public class Visitior
{
public void Visit<TFeature>(TFeature feature) where TFeature : IFeature
{
Console.WriteLine(typeof(TFeature) == feature.GetType());//True
}
}
static void Main(string[] args)
{
List<IFeature> features = new List<IFeature>
{
new FeatureA(),
new FeatureB()
};
Visitior visitor = new Visitior();
foreach (var item in features)
{
item.Accept(visitor);
}
}
这篇关于与调用接口实例泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!