2

很多时候我们需要引用服务器上的另一个文件。无论它只是一个图像,还是另一个asp页面。例如:

 if (success)
 {
    img1.ImageUrl = "RightArrow.jpg"
 }

这里的问题是,如果有人不小心将字符串“RightArrow.jpg”更改为“RghtArrow.jpg”,它不会导致编译时错误。并且可能需要很长时间才能注意到运行时错误。

那么这里有什么最佳实践吗?当然,我可以为此建立自己的小机制......但如果有任何内置的东西,我会徘徊。

可能是强类型的东西:

img1.ImageUrl = Images.RightArrow;
4

3 回答 3

2

Why not use Settings? If you did your code would be strongly typed, for example:

img1.ImageUrl = Settings.Default.Images.RightArrow

If you have a limited number of these resources this could be a good solution as you could even change the path/name without recompiling...

于 2012-10-09T20:04:06.667 回答
2

Can you just keep a List of the names of the pictures?

List<string> CollectionPictureUri = new List<string>(); 
CollectionPictureUri.Items.Add("RightArrow.jpg"); 

if (success)
 {
    img1.ImageUrl = CollectionPictureUri[0]; 
 }

Or if you use a Map, then the key could just be [RightArrow]

Then you can initialize all the items in one block of code and make sure they are correct in one place.

EDIT: You can also use asserts to validate that your strings resolve to the correct name. http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.assert%28v=vs.110%29.aspx

There are other testing techniques that might be useful to you. With visual studio you can prevent your code from building until errors like this are resolved.

于 2012-10-09T20:05:01.360 回答
1

您总是可以使用 T4 模板为实际存在的文件生成一个带有常量的类。这类似于 T4 MVC 模板对 /Content 目录的脚本和内容所做的事情;它在运行时扫描这些目录,并创建常量。

于 2012-10-09T20:06:51.987 回答