2013-07-25 83 views
2

的通用函数功能参数扩展方法是否有实现的扩展方法的泛型类型,它接受参数另一种类型的函数功能的方法吗?与其他类型

对于为例,类似这样的一个使用的东西:

myFirstObject.Extension<myOtherObject>(other => other.Prop); 

还是有更复杂的函数功能:

myFirstObject.Extension<myOtherObject>(other => other.Prop > 2 && other.Prop < 15); 

我发现了一些相关的问题像this one,但对我来说,我需要扩展方法内的泛型类型也是如此。

这就是我想出了:

public static bool Extension<TSource, TIn, TKey>(this TSource p_Value, Expression<Func<TIn, TKey>> p_OutExpression) 
{ return true; } 

然而,当我尝试使用它,它没有考虑到第二种类型。

我错过了什么吗?

回答

3

看看这个:

s => s.Length; 

怎么样编译器假设知道s是否是一个strings为数组或具有Length属性一些其他类型的?它不能,除非你给它一些信息:

(string s) => s.Length; 

哦,我们走了。所以,现在试试这个:

myFirstObject.Extension((myOtherObject o) => o.Prop > 2 && o.Prop < 15); 

,将工作,因为你告诉编译器它应该使用TIn,它可以计算出基于表达式使用什么TKey

0

当你调用C#泛型方法可以显式声明所有泛型类型的参数,或者你可以让他们所有的推断,但你不能有一些显式声明的一些推断。

所以,如果我有这样的方法:

public void Foo<X, Y>(X x, Y y) 
{ 
    /* Do somethhing */ 
} 

那么这里什么可行,什么不可行:

int a = 42; 
string b = "Hello, World!"; 

// Legal 
Foo(a, b); 
Foo<int, string>(a, b); 

//Illegal 
Foo<int>(a, b); 

你能做的最好的是上移至第一个泛型参数的但是它不会作为扩展方法工作。不过,你可能会喜欢这种方法。现在

public static class Class<TSource> 
{ 
    public static bool Method<TIn, TKey>(
     TSource p_Value, 
     Expression<Func<TIn, TKey>> p_OutExpression) 
    { 
     return true; 
    } 
} 

你可以这样调用:

Expression<Func<long, decimal>> f = 
    l => (decimal)l; 

var result = Class<int>.Method(a, f); 

但正如我所说,它不会作为一个扩展方法现在的工作。

+0

我可以用这个组合来amke调用其他方法的延伸,应该工作。我会发布我的结果。 – MicG

0

我发现,另一种解决方案是创建另一个,在参数使用类型的方法。

例如:

Void Extension(Type p_Type, [THE TYPE] p_Params) 
{ 
    MethodInfo realExtensionMethod = typeof([CLASS CONTAINING THE METHOD]).GetMethod("RealExtension"); 
    realExtensionMethod = realExtensionMethod.MakeGenericMethod(p_Type); 
    realExtensionMethod.Invoke(null, new object[] {p_Type, p_Params }); 
} 

Void RealExtension<TYPE>(params) 
{ 

} 

然后在使用时间:

Type objectType = typeof(myOtherObject); 
myFirstObject.Extension(objectType, other => other.Prop);