Extension method selection using generic types and Expressions
I have some extension methods that use an Expression parameter to pull in
a property member and act on it, and I have an overload for the specific
case where the member is an IEnumerable<>. However, it doesn't seem to
match the expected method overload when called from inside a generic class
(for r4 below). Outside of the class the correct method is selected.
What's going on here? Will this ever work or do I need to find a new
approach?
(This is in C# 5)
public class Test
{
public void MyTest()
{
// returns "Object"
var r1 = new MyClass<object>().Ext(a => a.Content);
// returns "Enumerable"
var r2 = new MyClass<IEnumerable<object>>().Ext(a => a.Content);
// returns "Object"
var r3 = new MyClass<object>().TestExt();
// returns "Object" (I was expecting "Enumerable")
var r4 = new MyClass<IEnumerable<object>>().TestExt();
// returns "Enumerable"
var r5 = new MyClass<int>().TestExt2();
}
}
public class MyClass<T>
{
public T Content { get; set; }
public IEnumerable<object> OtherContent { get; set; }
public string TestExt()
{
return this.Ext(a => a.Content);
}
public string TestExt2()
{
return this.Ext(a => a.OtherContent);
}
}
public static class MyExtensions
{
public static string Ext<T>(this T obj, Expression<Func<T,
IEnumerable<object>>> memberExpression)
{
return "Enumerable";
}
public static string Ext<T>(this T obj, Expression<Func<T, object>>
memberExpression)
{
return "Object";
}
}
No comments:
Post a Comment