开发者

Is there a way to cast a function

开发者 https://www.devze.com 2023-01-23 14:45 出处:网络
I think it would greatly simplify function overloading if I could just write the case that takes the most parameters and then simply stuff each case having less parameters with dummy params.For exampl

I think it would greatly simplify function overloading if I could just write the case that takes the most parameters and then simply stuff each case having less parameters with dummy params. For example..

// Add two int开发者_如何学编程egers
Func<int, int, int> addInts = (x, y) => { return x + y; };

// Add one to  an integer
Func<int, int> addOne = (x) => { return x++; };

// In this case Func takes 2 args and has 1 return
public int IntCalc(Func<int,int,int> operation, int param1, int param2)
{
    return operation(param1, param2);
}

// In this case Func takes 1 arg and has 1 return
public int IntCalc(Func<int, int> operation, int param1, int param2)
{
    // This cast would allow me to do the overload
    Func<int, int, int> castedOperation = (Func<int, int, int>)addOne;
    return IntCalc(castedOperation, param1, 0);
}

So is there a way to do this? Is this a horrible practice?


You can only cast if the parameter signatures are compatible. In your case you'd need to define a lamda since converting a function with one parameter to a function with two parameters makes no sense in general.

  Func<int, int, int> castedOperation = (i1,i2)=>addOne(i1);

If it's good practice depends on the contract of how the delegate will be used. If your functions with less parameters can fulfill that contract then this lamda based conversion is perfectly fine.

As a sidenode your addOne function is really ugly. While the increment of x has no effect because the parameter gets copied and thus only the copy is incremented and discared, implementing it as return x+1; would be much nicer than return x++; since you don't actually want to modify x.


Apart from the accepted answer you should also change the addOne to operation. So complete function would be

// In this case Func takes 1 arg and has 1 return
public int IntCalc(Func<int, int> operation, int param1, int param2)
{
    // This cast would allow me to do the overload
    Func<int, int, int> castedOperation = (i1,i2)=>operation(i1);
    return IntCalc(castedOperation, param1, 0);
}


If your all parameters are the same type you can use params

adder(bool sample, params int[] a)
{
  ....
}

adder(2,3,4);

also you can use Named Parameter in C# 4.0.

Your approach is useful in constructors (you can do this with them).

0

精彩评论

暂无评论...
验证码 换一张
取 消