字符串参数中的类型安全
我的具体问题是关于 ASP.NET MVC,但我确信答案可以应用于 ASP.NET 之外。
如何处理接受字符串参数但仍需要类型安全的函数?
在 ASP.NET 中,扩展方法 Html.ActionLink 有两个字符串类型的参数:string linkText、string actionName
。第一个参数是可以从资源加载的文本,但第二个参数是代码中存在的方法的名称。
一种选择是创建一个具有常量字符串的类,这样
Html.ActionLink("Blah blah", "MyAction");
就可以编写以下内容而不是编写:
Html.ActionLine("Blah blah", StrongType.MyAction);
其中 MyAction
是名为 StrongType
的类中的常量字符串。然而,当可以作为参数传递的方法和其他对象的数量增加时,管理就变得很痛苦。
第二种选择是使用反射以某种方式加载函数的名称,但这似乎太昂贵了。
有更好的方法吗?如何确保字符串参数中没有像前面提到的那样的拼写错误?
My specific question is about ASP.NET MVC but I am sure that the answers can be applied outside ASP.NET.
How do you deal with functions that accept string arguments but still you want type safety?
In ASP.NET, the extension method Html.ActionLink has two arguments of type string: string linkText, string actionName
. The first argument is a text that can be loaded from a resource but the second argument is the name of a method that exists in code.
One option would be to create a class with constant strings so instead of writing
Html.ActionLink("Blah blah", "MyAction");
one could write:
Html.ActionLine("Blah blah", StrongType.MyAction);
Where MyAction
is a const string in a class called StrongType
. However, this becomes a pain to manage when the number of methods and other objects that can be passed as arguments increases.
A second option would be to load somehow the name of the function using Reflection but this seems too expensive.
Is there a better way of doing it? How do you make sure that you don't have typos in string arguments like the ones mentioned before?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 ActionLink 扩展方法,它可以让您避免使用这些魔术字符串。
您需要引用
Microsoft.Web.Mvc
,它是 ASP.NET MVC 3 Futures 的一部分,可在 http://aspnet.codeplex.com/releases/view/58781。You can use the ActionLink extension method that allows you to avoid the use of these magic string.
You'll need to reference
Microsoft.Web.Mvc
which is part of ASP.NET MVC 3 Futures and available at http://aspnet.codeplex.com/releases/view/58781.我认为莱斯特的回答适合这个具体案例。但在更一般的情况下,您确实需要定义常量并使用它们。是的,这很痛苦,但是您可以在节省的时间中设置很多常量,而不必追踪由于在您的意思是“黄色”时给出参数“黄色”而导致的错误。
现在,如果您是设计被调用方法的人,当您确实有一组它可以接受的常量值时,请不要将其设置为字符串参数。将其设为枚举。
I think Lester's answer is appropriate for this specific case. But in the more general situation, you really need to define the constants and use them. Yes, it is a pain, but you can set up a lot of constants in the time you save not having to track down a bug caused by giving an argument "Yellow" when you meant "yellow".
Now, if you are person designing the method being called, don't make it a string argument when you really have a set of constant values it will accept. Make it an enum.