I've read that it is usually bad practice to extend System.Object, which I do agree with.
I am curious, however, if the following would be considered a useful extension method, or is it still bad practice?
It is similar to extending System.Object but not exactly,
public static R InvokeFunc<T, R>(this T inpu开发者_如何学Pythont, Func<T, R> func)
{
return func.Invoke(input);
}
This essentially allows any object to invoke any function that takes that object as a parameter and returns R, whether that function belongs to the object or not. I think this could facilitate some interesting 'inversion of control', but not sure about it overall.
Thoughts?
Well there are really two points here:
1) Whether it is a good idea to create an extension method with this T
so it will be applied to all types?
2) Whether the particular extension method described is useful?
For the 1st question the answer is sometimes but depends on the context. You can have an extension method apply to all classes just like linq does ensuring that you pick an appropriate namespace. I would think creating this type of extension method within the System namespace a bad idea but if it were more targeted then perhaps it would be useful.
For the 2nd since the invoke is immediate then the choice of syntax is as follows
int res = other.InvokeFunc<Other, int>(Callback);
var res2 = (new Func<Other, int>(Callback))(other);
var res3 = Callback(other);
Looking at that then a simple call to the method passing the instance in is more natural and typical, however if your extension method becomes more elaborate then I go back to my first point on that it depends on the context (which could help with encapsulation).
All this does is that it gives you the ability to refer to a method as a parameter which is in fact what delegates already allow you in C#.
I don't see it being more useful (in case of IoC) than a delegate of type Func<T,R>
in your case. It's just another way of invoking it.
UPDATE
As mentioned in the comments, I think this method only helps you in creating delegates more efficiently. But either way, you do not use the created delegate any further since you invoke it immediately. So an extension method like this would make more sense to me:
public static Func<R> InvokeFunc<T, R>(this T input, Func<T, R> func)
{
return () => func(input);
}
精彩评论