编程语言
首页 > 编程语言> > c#-反射-ui对象自动为model对象赋值-简单实验

c#-反射-ui对象自动为model对象赋值-简单实验

作者:互联网

1.代码 

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello word");
            Program p = new Program();
            p.main();
            Console.ReadKey();
        }
        private void main() {
            A a = new A();
            Form1 f = new Form1();
            createModel(a,f);
            a.display();
        }
        class Form1 : Form {
            public TextBox a;
            private TextBox b;
            public Form1() {
                a = new TextBox();
                a.Text = "1";
                b = new TextBox();
                b.Text = "str";
            }
        }
        class A {
            public int a;
            private string b;
            public void display() {
                Console.WriteLine("a:"+a);
                Console.WriteLine("b:"+b);
            }
        }
        private void createModel(Object o, Form f)
        {
            Type type = o.GetType();
            Type typp2 = f.GetType();
            foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                Object filed = fieldInfo.GetValue(o);
                Object o2 = typp2.GetField(fieldInfo.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(f);
                if (o2.GetType().Name == "TextBox")
                {
                    TextBox t = (TextBox)o2;
                    string str = t.Text;
                    if (str != null && str.Trim().Length > 0)
                    {
                        String typeNeme = fieldInfo.FieldType.Name;
                        if (typeNeme == "Int32")
                        {
                            int invalue = int.Parse(str);
                            fieldInfo.SetValue(o, invalue);
                        }
                        else if (typeNeme == "String")
                        {
                            fieldInfo.SetValue(o, str);
                        }
                    }
                }
            }
        }
    }
}

2.运行 

标签:c#,System,BindingFlags,ui,str,fieldInfo,using,model,TextBox
来源: https://blog.csdn.net/xie__jin__cheng/article/details/114603573