本文介绍了在C#中强制命名参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#4引入了一个名为,该功能特别有用在类似

C# 4 introduced a feature called named arguments which is especially useful in scenarios like

int RegisterUser(string nameFirst, string nameLast, string nameMiddle, string email)

有没有办法强制使用命名参数?也许某些属性适用于我不知道的方法或编译器开关?我想可以使用代码检查器工具完成此操作,但只是想知道是否还有其他方法。

Is there a way to force using named arguments? Maybe some attribute to apply to a method or a compiler switch I'm not aware of? I guess it can be done with code inspector tools but just want to know if there is other way.

ps

对于那些感兴趣的人,为什么可能需要它以及为什么不仅仅使用类/结构来利用在某些情况下是不可能的。就像对不在您的控件或怪异的代码约定中的库的调用一样,您必须服从。

For those interested why one may need it and why not just use a class/struct to utilize object initializers there are scenarios when it's impossible. Like calls to libraries not in your control or weird code conventions you have to obey.

推荐答案

不,不是C#语言。如果提供了所有参数,它将始终接受位置参数。

No, not in the C# language. It will always accept positional parameters if all the parameters are supplied.

您可以或来强制执行此操作-如评论中所指出,您可能会对StyleCop规则感兴趣(感谢Kris)。

You could build a custom FxCop rule or an StyleCop rule to enforce this - as pointed out in the comments, it is likely a StyleCop rule you would be interested in (thanks to Kris).

这篇关于在C#中强制命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 23:43