The*_*Man 2 .net c# xml winforms
好的,我已经用谷歌搜索了将近两天,并且尝试了几乎所有与此错误相关的 SO 解决方案,但没有任何效果。大多数有关此问题的问题是关于 Click-once 应用程序、JSON、Web 应用程序等的安全设置。但对于普通的旧 Winforms 应用程序则没有任何问题。
这是完整的错误
System.TypeAccessException:尝试通过方法“Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterSystemSetup.Write3_SystemSetup(System.Object)”访问类型“DataFacture.Common.Globals+SystemSetup”失败。在 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterSystemSetup.Write3_SystemSetup(Object o)
这是“SystemSetup”类的简化版本
public class SystemSetup
{
private string machineId, windowsVersion;
public SystemSetup() { }
public SystemSetup(string machineId, string windowsVersion)
{
this.machineId = machineId;
this.windowsVersion = windowsVersion
}
public string MachineID { get { return machineId; } set { machineId = value; } }
public string WindowsVersion{ get { return windowsVersion; } set { windowsVersion= value; } }
}
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试使用以下代码和“writer.Serialize(wfile, objectSerializer);”生成 SystemSetup 对象的 XML 行,发生错误
public static void WriteXML(Object objectSerializer, String XMLPath, String FileName)
{
try
{
if (XMLPath.Substring(XMLPath.Length - 1, 1) != @"/")
XMLPath = String.Format("{0}\\", XMLPath);
XmlSerializer writer = null;
Type objectType = objectSerializer.GetType();
switch (objectType.Name)
{
case "SystemSetup":
writer = new XmlSerializer(typeof(Globals.SystemSetup));
break;
}
var wfile = new System.IO.StreamWriter(String.Format("{0}{1}", XMLPath, FileName));
writer.Serialize(wfile, objectSerializer);
wfile.Close();
}
catch (Exception ex)
{
ErrorHandler.ShowErrorMessage(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个winforms 应用程序。它不是单击一次。而且我没有对任何程序集实施任何安全限制。此外,没有我从这里调用的第 3 方程序集。
编辑:以上位于相同的命名空间中,但位于不同的类文件中。如果我把它们放在一个类文件中,它就可以工作。不知道这是否有帮助
经过大量的摆弄。我发现了问题;菜鸟错误就在我这边。调用“SystemSetup”对象的“Globals”类未指定为私有或公共。我只是
static class Globals
{
public class SystemSetup
{
//My code here
}
}
Run Code Online (Sandbox Code Playgroud)
在设计时,没有任何问题。您可以访问“Globals”中的所有类。但是,在运行时,调试器无法访问“Globals”类,因此您需要将其指定为“public”
public static class Globals
{
public class SystemSetup
{
//My code here
}
}
Run Code Online (Sandbox Code Playgroud)
我完全忽略了这一点。我认为这是理所当然的,因为我可以在设计时访问该类并且编译器在构建解决方案时没有问题,那么它应该在运行时工作,并且由于“SystemSetup”类是公开的,我认为它会起作用。OOP 编程 101,完全错过了。