I have a Class Foo with a number of methods that return DataSet. I want to be able to pass a Func<DataSet> process
into a method that can call the req开发者_如何学Gouested method on an instance of Foo that the calling method doesn't know. Something like this:
DataSet CommonMethod( Func<DataSet> process )
{
Foo foo = GetFooFromSomewhere( );
return foo.process( ); // <-- obviously, not this way!
}
called with something like
DataSet ds1 = CommonMethod( GetDataSetForX );
DataSet ds2 = CommonMethod( GetDataSetForY );
where GetDataSetForX/Y are methods of Foo.
[NOTE: I don't own Foo - I can't make changes to it.]
Do it like this:
DataSet CommonMethod( Func<Foo, DataSet> process )
{
Foo foo = GetFooFromSomewhere( );
return process(foo);
}
// call it like this:
DataSet ds1 = CommonMethod(f => f.GetDataSetForX());
DataSet ds2 = CommonMethod(f => f.GetDataSetForY());
But honestly, in your simple example, I don't see the benefit. Why not just do it the "old fashioned way"?
DataSet ds1 = GetFooFromSomewhere().GetDataSetForX();
DataSet ds2 = GetFooFromSomewhere().GetDataSetForY();
精彩评论