[英]What type should I use to indicate an argument is a filename in C#?
My functions needs a file name so it can read and/or write to this file. 我的函数需要一个文件名,以便它可以读取和/或写入该文件。 I could use a simple string for this purpose 为此,我可以使用一个简单的字符串
void myFunc(string filename)
but I'd rather have some more type-safety by requiring a more specialized type and not detect that ""
is no valid filename within the method. 但我宁愿通过要求更专业的类型而不是检测""
在方法中没有有效的文件名而具有更多的类型安全性。
The class File
doesn't work because it's static. 类File
不起作用,因为它是静态的。
The class FileInfo
could be used but I cannot remember that I've come across a filename argument of this type. 可以使用类FileInfo
,但我不记得我遇到过这种类型的文件名参数。
In personal projects I made up my own class that simply does some checking if the filename is well-formed etc. so eg an exception is thrown upon creation of the filename and not in the method itself. 在个人项目中,我编写了自己的类,只是检查文件名是否格式正确等等。例如,在创建文件名时抛出异常,而不是在方法本身。
Since the new project is of wider scope I'd thought it would be better to use a common standard to not confuse other users (or my future self in some weeks). 由于新项目范围更广,我认为最好使用通用标准,以免混淆其他用户(或者在未来几周内我的未来)。
If you are finding FileInfo insufficient for some reason, you may be dealing with the file name in a manner that more closely matches a System.Uri . 如果由于某种原因发现FileInfo不足,您可能会以更接近System.Uri的方式处理文件名。 A Uri is not necessarily always related to a file, but a file path can be an example of a Uri, and Microsoft's implementation supports this with the IsFile property. Uri不一定总是与文件相关,但文件路径可以是Uri的示例,而Microsoft的实现通过IsFile属性支持它。 One could imagine a FileUri class which inherits from Uri and IsFile is forced. 可以想象一个强制继承Uri和IsFile的FileUri类。
It is probably worth mentioning that in most of the MSDN snippets I've been looking at, file paths and names are just passed as strings. 值得一提的是,在我一直关注的大多数MSDN片段中,文件路径和名称只是作为字符串传递的。 This may just be for convenience though. 这可能只是为了方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.