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

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

问题描述

我今天刚刚在 C# 中遇到了一些我以前没有想到的东西.我的班级中有两种方法,一种是另一种的重载.它们是这样声明的:

  1. public void RequirePermissions(params string[] 权限)...

  2. public void RequirePermissions(string message, params string[] 权限)...

在我的代码中,我尝试像这样调用第一个:

RequirePermissions("Permission1", "Permission2");

...期待它调用第一个重载.好吧,它称为第二次重载.在这种情况下,我可以让它调用第一个方法的唯一方法是手动传递一个 string[] 对象,如下所示:

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

现在,这种行为不会让我感到困惑,因为我知道编译器无法根据我提供的参数判断我真正想要调用哪个方法.但是如果我不小心,这可能会在我的代码中被忽视.当遇到上述情况时,微软似乎应该让编译器抛出错误.有没有人对此有任何想法?除了我发布的解决方案"之外,还有其他方法可以调用第一个重载吗?

解决方案

就我个人而言,我会这样做:

  1. public void RequirePermissions(params string[] 权限)...

  2. public void RequireMessageAndPermissions(string message,params string[] 权限)...

人们有时太喜欢重载了,当你把它与对 params 关键字的热爱结合起来时,你只会增加最终不得不接管你的代码的人的混淆程度.

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)...
    

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" });

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)...
    

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天全站免登陆