我在我的 ASP.NET MVC 应用程序中使用了一个资源文件,当我分析项目的代码问题时,ReSharper 警告我找不到 System.Windows.Forms 引用。
我真的应该在我的 Web 应用程序中引用 System.Windows.Forms
吗?为什么 resx 文件中仍然需要它?
当我在 XML 编辑器中打开 resx 文件时,我看到它引用了程序集:
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="..." type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>...;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
我真的不喜欢我的 Web 应用程序链接到任何 System.Windows.Forms
相关的东西。
这是为什么呢?有没有比使用这些 resx 文件更好的管理 Web 应用程序资源的方法?
最佳答案
资源文件格式记录在这里:Creating Resource Files
.resources 格式是一种二进制格式,允许将资源嵌入到运行时 .dll 或 .exe 中。它可以使用 mscorlib 程序集中存在的类进行读取和写入:ResourceReader 和 ResourceWriter
.ResX 文件格式是一种基于 XML 的格式,可以使用 System.Windows.Forms 程序集中存在的类进行读写:ResXResourceReader 和 ResXResourceWriter . (当您创建一个新的 ResX 文件时,XML 架构实际上在文件中的注释中进行了解释)。
只有 .resources 应该嵌入到运行时可执行文件中。这就是为什么 .ResX 格式可以被视为 .resources 格式的“源文件格式”。
现在,在这些格式中,您几乎可以嵌入任何类型的资源,但您必须告诉系统如何嵌入,因为存储在这些文件中的数据实际上是数据的序列化版本。 对于存储字符串,您不需要对外部反序列化器类有任何额外的依赖性,但对于其他类型(如图标、位图等),您需要。 Visual Studio 编辑器使用您在文件中看到的 System.Windows.Forms(反)序列化程序类。因此,您需要隐式加载 System.Windows.Forms 才能使这些非字符串数据反序列化。
因此,如果您使用 Visual Studio 创建了非字符串资源,您将对 System.Windows.Forms 有一个隐式引用,是的。 如果你不想要这个,删除所有对这些非字符串资源的引用(你也可以很容易地手动调整文件)并使用其他方式存储你的 Assets (例如,Build Action 上的'Embedded Resource',或普通的“assets "您网站中的目录)。
请注意,理论上您也可以使用自己的类来存储自定义数据,如下所示:Resources in .resx File Format
The following example shows an Int32 object saved in a .resx file, and the beginning of a bitmap object, which holds the binary information from an actual .gif file.
<data name="i1" type="System.Int32, mscorlib"> <value>20</value> </data> <data name="flag" type="System.Drawing.Bitmap, System.Drawing, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value> AAEAAAD/////AQAAAAAAAAAMAgAAADtTeX… </value> </data>
据我所知,Visual Studio 编辑器不支持像这样的自定义类来编辑 .ResX 文件。
关于c# - Web 应用程序中对 System.Windows.Forms 的资源和引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32249988/