构造 ArgumentException 时如何以编程方式确定参数名称?
构造 ArgumentException 时,一些重载采用一个字符串,该字符串是无效参数的参数名称。 我认为每当我更改方法的参数名称时不必记住更新此 ctor 参数会很好。 有没有一种简单的方法可以使用反射来做到这一点?
更新:感谢迄今为止的 2 位受访者。 你们都很好地回答了这个问题,但解决方案仍然让我感到头痛。 (好吧,有点头疼,但仍然......)解释一下,如果我稍后要重新排序参数 - 或者删除较早的参数 - 我会必须记住再次更改我的异常构造代码。 有没有一种方法可以使用类似的方法来
Object.ReferenceEquals(myParam, <insert code here>)
确保我正在处理相关参数? 这样,编译器就会介入以防止我错误地构造异常。
也就是说,我开始怀疑原来问题的“简单”部分并没有那么明显。 也许我应该忍受使用字符串文字。 :)
When constructing an ArgumentException, a couple of the overloads take a string that is the invalid argument's parameter name. I figure it would be nice to not have to remember to update this ctor param whenever I change the method's param name. Is there a simple way to do this using reflection?
Update: thanks to the 2 respondents so far. You both answer the question well, but the solution still leaves me with a maintenance headache. (Okay, a tiny headache, but still...) To explain, if I were to reorder the params later -- or remove an earlier param -- I'd have to remember to change my exception-construction code again. Is there a way I can use something along the lines of
Object.ReferenceEquals(myParam, <insert code here>)
to be sure I'm dealing with the relevant parameter? That way, the compiler would step in to prevent me badly constructing the exception.
That said, I'm starting to suspect that the "simple" part of the original question not that forthcoming. Maybe I should just put up with using string literals. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
反思不适合于此。
你必须忍受记住才能把事情做好。
幸运的是,FxCop(或团队系统代码分析)将通过指出任何不匹配来帮助您。
Reflection is not appropriate for this.
You'll have to put up with remembering to get it right.
Fortunately FxCop (or Team System Code Analysis) will help you by pointing out any mismatches.
您可以为此使用表达式树,这将以一些奇怪的语法为代价获得您想要的结果。 例如,
其中 NameOfVariable 定义为:
如果将 UnaryExpression 以外的任何内容传递给 NameOfVariable,则在运行时也有可能崩溃。
如果这段代码也导致 FxCop 抱怨,我不会感到惊讶,并且如 Joe 提到使用 FxCop 可能是实现此目的的最佳方法。
You could use an expression tree for this, which will get you want you want at the expensive of some odd syntax. E.g.
Where NameOfVariable is defined as:
This also has the chance of crashing at runtime if you pass anything other than a UnaryExpression to NameOfVariable.
I wouldn't be surprised if this code also causes FxCop to complain, and as Joe mentions using FxCop is the probably the best way of doing this.