0
点赞
收藏
分享

微信扫一扫

c# .net 将字符串拼接后再转成对象输出其值,将一个string的字符串转成一个对象变量,反射...


反射 相似文件名值的遍历

C#类源码

using System; 
using System.Reflection;

namespace tttt 
{ 
	class ttt 
	{ 
		public string String1 = "aaaa";
		public string String2 = "bbbb";
		public string String3 = "cccc";
		public string String4 = "dddd";
		public string String5 = "eeee";
		public string String6 = "ffff";

		static void Main(string[] args) 
		{ 
			new ttt();
		}
		public ttt()
		{
			string temp = "";
			Type type = this.GetType();
			for (int i = 1; i < 7; i++)
			{
				FieldInfo fi = type.GetField("String" + i.ToString());
				temp += fi.GetValue(this).ToString();
			}
			Console.WriteLine("将字符串拼接后再转成对象输出其值");
			Console.WriteLine(temp);
			Console.Read(); 
		}
	}
}





winform里的源码



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

[color=red]using System.Reflection;[/color]


namespace FloorDesign
{
    public partial class Form1 : Form
    {
	public string ddd1 = "aa";
	public string ddd2 = "bb";
	public string ddd3 = "cc";
	public string ddd4 = "dd";

        public Form1()
        {
             InitializeComponent();

	    string temp = "";
	    Type type = this.GetType();
             for (int i = 1; i < 5; i++)
	    {
	        FieldInfo fi = type.GetField("ddd" + i.ToString());
	        temp += fi.GetValue(this).ToString();
	    }
	MessageBox.Show("将字符串拼接后再转成对象输出其值"
);	
         MessageBox.Show(temp);
        }
}




虽然很多人都说这样做没有意义



可是我觉得有意义的,假设这样,只是假设哈,不用数组,就一个一个变量去定义



一个类里有定义了2万1000个变量


其中要得到1000个


这1000个是这样定义的

for(int = 0 ;i<1000,i++) 

{ 

 string "abc"+i.ToString(); 

}




然后给这1000个变量赋值



如果写1000个变量按个去赋,不累死人才怪



我能想到的最容易的方法就是上边的那个 将字符串拼接后再转成对象 的方法



如果您有好方法,请不吝赐教



黑色头发:http://heisetoufa.iteye.com


举报

相关推荐

0 条评论