Metaprogramming in C# by Einar Ingebrigtsen

Metaprogramming in C# by Einar Ingebrigtsen

Author:Einar Ingebrigtsen
Language: eng
Format: epub, pdf
Publisher: Packt Publishing Pvt Ltd
Published: 2023-06-16T00:00:00+00:00


Encapsulating type discovery

In Chapter 4, Reasoning about Types Using Reflection, we introduced a class called Types, which encapsulates the logic used in finding types. This is a very powerful construct for enabling software to be extensible. We can make it a little bit better and build a construct on top of it that simplifies its use.

In the Types class, we have a method called FindMultiple(), which allows us to find types that implement a specific type. A small improvement on this would be to allow us to represent the different types we want implementations of by taking a dependency in a constructor of a specific type that describes this.

Important note

You’ll find the implementation of this in the Fundamentals part of the repository mentioned in the Technical requirements section.

The concept is basically to have the type represented as an interface, as follows:

public interface IImplementationsOf<T> : IEnumerable<Type> where T : class { }

The interface takes a generic type that describes the type whose implementations you’re interested in. It then says it is an enumerable of Type, which makes it possible for you to iterate over it directly. The generic constraint of class is there to limit the scope of the types you can work with, since it wouldn’t be useful to allow primitive types such as int, which aren’t inheritable.

The implementation of the interface is straightforward and looks as follows:

public class ImplementationsOf<T> : IImplementationsOf<T> where T : class { readonly IEnumerable<Type> _types; public ImplementationsOf(ITypes types) { _types = types.FindMultiple<T>(); } public IEnumerator<Type> GetEnumerator() { return _types.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _types.GetEnumerator(); } }

The code takes ITypes as dependencies, as it will use it to actually find the implementations.

Discovering types is one thing, and this makes the approach a little bit nicer by making the code more readable and clearer. But this only gives you the type. A more common method is to get not only the type but also its instances.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.