AlbedoOrg / Albedo

A .NET library targeted at making Reflection programming more consistent, using a common set of abstractions and utilities
MIT License
166 stars 18 forks source link

ReflectionElementFactory #24

Closed ploeh closed 11 years ago

ploeh commented 11 years ago

It often happens (at least in the AutoFixture code base) that you have an object that may be some Reflection object, like PropertyInfo, or ParameterInfo, but you don't know which.

The whole point of Albedo is to provide a polymorphic API over Reflection, so it'd be nice to be able to automatically translate from object to IReflectionElement.

Something like

var re = obj.AsReflectionElement()

However, as far as I can tell, there are at least two different scenarios:

Perhaps there are more scenarios? This indicates to me that we should implement this as a proper extensible Factory class.

Something like this should do the trick:

public interface IReflectionElementPipe<T>
{
    IEnumerable<IReflectionElement> Pipe(IEnumerable<T> source);
}

(I'm not quite sure about the name, so suggestions are welcome...)

While T would often be object, the generic type argument exists to support scenarios where you know that you can only receive objects that implement IMemberInfo, in which case you can declare the T as IMemberInfo...

Now you can implement an individual pipe like:

public class PropertyInfoElementPipe<T> : IReflectionElementPipe<T>
{
    public IEnumerable<IReflectionElement> Pipe(IEnumerable<T> source)
    {
        return source
            .OfType<PropertyInfo>()
            .Select(pi => new PropertyInfoElement(pi));
    }
}

Given all these, you could implement the actual factory as a composite of all those...

ploeh commented 11 years ago

FYI, I've now pushed CompositeReflectionElementRefraction<T> to master...