调用具有接口实例的通用方法 [英] Calling a generic method with interface instances

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

问题描述

作为这一个的后续问题

  public interface IFeature {} 

public class FeatureA:IFeature {}

IFeature a = new FeatureA();
激活(a);

private static void Activate< TFeature>(TFeature featureDefinition)其中TFeature:IFeature
{

}
pre>

我不知道,一旦 FeatureA 被转换为 IFeature 通用方法将始终将 IFeature 作为类型参数。



我们有一个服务,为我们提供列表功能(列表< IFeature> )。如果我们想迭代这些功能,传递一般的方法,我想没有办法得到通用方法的具体类型,而不是




  • 使用反射

  • 使用动态变量来确定运行时的类型(



由于反思非常昂贵,我想使用动态转换。有什么不利之处吗?在某种程度上我觉得很脏: - )

解决方案

您可以使用访客模式,假设您可以修改代码库。否则,使用动态。

  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。访问(本);
}
}

public class Visitior
{
public void访问< TFeature>(TFeature功能)其中TFeature:IFeature
{
Console.WriteLine(typeof(TFeature)== feature.GetType()); // True
}
}

static void Main(string [] args)
{
列表< IFeature> features = new List< IFeature>
{
new FeatureA(),
new FeatureB()
};

Visitior visitor = new Visitior();
foreach(var item in features)
{
item.Accept(visitor);
}
}


As a followup question to this one

public interface IFeature  {  }

public class FeatureA : IFeature { }

IFeature a = new FeatureA();
Activate(a);

private static void Activate<TFeature>(TFeature featureDefinition) where TFeature : IFeature
{

}

I undestand, that once the FeatureA is casted to IFeature the generic method will always get IFeature as type parameter.

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

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天全站免登陆