C#PARAMS用相同类型的两个参数关键字 [英] C# params keyword with two parameters of the same type

查看:185
本文介绍了C#PARAMS用相同类型的两个参数关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正好遇到与C#今天的东西,我没有想到过的。我在我的类两种方法,一种其它的过载。他们宣称,像这样:

I just encountered something with C# today that I hadn't thought of before. I have two methods in my class, one an overload of the other. They are declared like so:

1) public void RequirePermissions(params string[] permissions)...
2) public void RequirePermissions(string message, params string[] permissions)...

在我的code,我试着拨打第一个像这样:

In my code, I tried to call the first one like so:

RequirePermissions("Permission1", "Permission2");

...期待它调用第一个过载。那么它称为第二超载。我能得到它调用第一个方法,在这种情况下,唯一的办法就是手动传递一个字符串[]的对象,像这样:

...expecting it to call the first overload. Well it called the second overload. The only way I can get it to call the first method in this case is to manually pass a string[] object like so:

RequirePermissions(new string[] { "Permission1", "Permission2" });

现在,此行为不会迷惑我,因为我明白,编译器无法知道哪种方法我其实是想根据我提供的参数来调用。但我不小心,这可能在我的code还没有受到重视。它好像微软应该让编译器抛出一个错误,当它遇到的情况类似上面。没有人对此有什么看法吗?有另一种方式来调用比解决方案以外的第一个重载我张贴?

Now, this behavior doesn't confuse me because I understand that the compiler can't tell which method I actually wanted to call based on my provided parameters. But was I not careful this could have gone unnoticed in my code. It seems as though Microsoft should have made the compiler throw an error when it encountered a situation like above. Does anyone have any thoughts on this? Is there another way to call the first overload other than the "solution" I posted?

推荐答案

就个人而言,我会做这种方式:

Personally, I'd do it this way:

1) public void RequirePermissions(params string[] permissions)...
2) public void RequireMessageAndPermissions(string message, 
       params string[] permissions)...

人,也爱上有时超载,当你结合,与为 PARAMS 关键字爱,你只是增加了任何人最终都有拿混乱,层次在你的code。

People fall too in love with overloading sometimes, and when you combine that with a love for the params keyword, you just increase the confusion level for whomever eventually has to take over your code.

这篇关于C#PARAMS用相同类型的两个参数关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆