与调用接口实例泛型方法 [英] Calling a generic method with interface instances

查看:108
本文介绍了与调用接口实例泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为后续问题来这个

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

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆