Invocation of a generic method with an interface

As a follow up question this

public interface IFeature { } public class FeatureA : IFeature { } IFeature a = new FeatureA(); Activate(a); private static void Activate<TFeature>(TFeature featureDefinition) where TFeature : IFeature { } 

I do not know that after FeatureA is passed to IFeature , the general method will always have IFeature as a type parameter.

We have a service that provides us with a list of functions ( List<IFeature> ). If we want to iterate over these functions, passing each of the general method, I think that there is no way to get a specific type in a general method other than

Since reflection is very expensive, I would like to use a dynamic movie. Is there a disadvantage to calling a method this way? Somehow I feel dirty when I do this :-)

+6
source share
2 answers

You can use the visitor template as follows, assuming that you can change your code base. 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); } } 
+5
source

You can get a type object for a generic / (not generic) type with typeof:

  public static T Parse<T>(String value) { object result = default(T); var typeT = typeof (T); if (typeT == typeof(Guid)) { result = new Guid(value); } else if (typeT == typeof(TimeSpan)) { result = TimeSpan.Parse(value); } else { result = Convert.ChangeType(value, typeT); } return (T)result; } 

My simple method returns T. And this is the key. It must be shared so that the developer can specify the type of return value. If a method does not return a common one and accepts only one, there are several reasons to make it general. To avoid box / unbox operations in method arguments or to solve a situation when a method takes an argument of different types that are not inherited from a common base class / interface. And that is none of your business. Thus, the method in your code should not be general. Just enter the argument as IFeature and use is / as / GetType ():

 private static void Activate(IFeature feature) { if (feature is FeatureImplementationA) { //Do something... } } 
0
source

All Articles