FieldInfo

作者:追风剑情 发布于:2018-11-27 15:12 分类:C#

示例一

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace Test2
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B();
            Type at = a.GetType();
            Type bt = b.GetType();
            FieldInfo bf;
            foreach(FieldInfo field in at.GetRuntimeFields())
            {
                bf = bt.GetRuntimeField(field.Name);
                bf.SetValue(b, field.GetValue(a));
            }
            Console.Read();
        }
    }

    public struct Config
    {
        public string k;
        public string v;
    }

    public class A
    {
        public string name = "xiao";
        public int age = 18;
        public Config[] cfgs;

        public A()
        {
            Config cfg0 = new Config();
            cfg0.k = "k1";
            cfg0.v = "v1";
            Config cfg1 = new Config();
            cfg1.k = "k2";
            cfg1.v = "v2";
            cfgs = new Config[2];
            cfgs[0] = cfg0;
            cfgs[1] = cfg1;
        }
    }

    public class B
    {
        public string name = "";
        public int age = 0;
        public Config[] cfgs;
    }
}

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号