简体   繁体   English

访问C#中非序列化类中包含的序列化对象

[英]Accessing a serialized object contained in non-serialized class in c#

I have a program code like this 我有这样的程序代码

namespace Ask{
    public class TestSerialize
    { 
        [Serializable]
        public struct position
        {
            public int x;
            public int y;
        }
    };


    public class SubTest:Panel
    {
        public TestSerialize.position pos;
    }

    public class Test
    {
        public static void main(String args[])
        {
            SubTest t=new SubTest();
            Console.WriteLine(t.pos.x);
        }
    }
}

now accessing pos.x in class test shows warning 现在在类测试中访问pos.x显示警告

Warning Accessing a member on 'Ask.SubTest.pos' may cause a runtime exception because it is a field of a marshal-by-reference class 警告访问“ Ask.SubTest.pos”上的成员可能会导致运行时异常,因为它是按引用编组类的字段

I am weak with serialization concepts so please suggest how to mitigate this warning ? 我对序列化概念比较虚弱,因此请提出如何减轻这种警告的建议? Is there a workaround or i need to redesign ? 有解决方法还是我需要重新设计? I dont want to catch an exception here.Anyway to avoid it ? 我不想在这里遇到异常。无论如何要避免它?

You have to change x and y of struct to public. 您必须将struct的x和y更改为public。

[Serializable]
public struct position
{
    public int x;
    public int y;
}

I think issue with struct members make them public. 我认为结构成员的问题使他们公开。 See my below program complete copy of your code. 请参阅下面的程序完整代码副本。 Only struct members are public and it compile fine without any warning. 只有结构成员是公开的,并且可以在没有任何警告的情况下进行编译。

public class Program
{
    public static void Main(string[] args)
    {
        SubTest t = new SubTest();
        Console.WriteLine(t.pos.x);
    }
}

public class TestSerialize
{
    [Serializable]
    public struct position
    {
        public int x;
        public int y;
    }
};


public class SubTest
{
    public TestSerialize.position pos;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM