System.TypeAccessException:尝试方法“X”访问类型“Y”失败

时间:2015-10-07 08:32:50

标签: c# .net xml winforms

好的,我已经用Google搜索了近两天,我尝试了几乎所有与此错误相关的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; } }
    }

现在我正在尝试使用以下代码生成SystemSetup对象的XML,并在'writer.Serialize(wfile,objectSerializer);'行,发生错误

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);
        }
    }

这是一个winforms应用程序。它不会单击一次。我没有对任何程序集强制执行任何安全限制。此外,我没有从这里打电话给第三方组件。

编辑:以上是在相同的命名空间中,但在单独的类文件中。如果我将它们放入一个类文件中,它就可以了。不确定是否有帮助

1 个答案:

答案 0 :(得分:3)

经过大量的摆弄。我发现了问题;菜鸟的错误在我身边。我调用“SysytemSetup”对象的“Globals”类未被指定为私有或公共。我只是

static class Globals
{
    public class SystemSetup
    {
        //My code here
    }
}

在设计时,没有任何问题。您可以访问“Globals”中的所有类。但是,在运行时,调试器无法访问“Globals”类,因此您需要将其指定为“public”

public static class Globals
{
    public class SystemSetup
    {
        //My code here
    }
}

我完全忽视了这一点。我理所当然地认为,因为我可以在设计时访问该类并且编译器在构建解决方案时没有问题,所以它应该在运行时工作,并且由于“SystemSetup”类是公共的,我认为它可以工作。 OOP编程101,完全错过了它。