2010-11-03 65 views
2

我认为这将大大简化函数重载,如果我只能写出大多数参数的情况,然后用虚拟参数简单地填充每个具有较少参数的情况。例如..有没有方法来施放函数

// Add two integers 
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); 
} 

那么有没有办法做到这一点?这是一种可怕的做法吗?

回答

2

只有参数签名兼容时才能投射。在你的情况下,你需要定义一个lamda,因为将具有一个参数的函数转换为具有两个参数的函数通常是没有意义的。

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

如果是好的做法取决于委托人如何使用合同。如果您的参数较少的功能可以满足该合同,那么这种基于lamda的转换是完全正确的。

作为一个sidenode您的addOne功能是真的丑陋。尽管x的增量没有效果,因为参数被复制,因此只有副本被增加和放大,但实现它作为return x+1;会比return x++;好得多,因为您实际上不想修改x。

1

除了接受的答案之外,您还应该将addOne更改为操作。因此,完整的功能将是

// 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); 
} 
1

如果你的所有参数都是同一类型,你可以使用params

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

adder(2,3,4); 

你也可以使用C#4.0 Named Parameter

你的方法在构造函数中很有用(你可以用它们来做到这一点)。

相关问题