C# 通过类名称字符串获取类实例,枚举名称字符串获取所有枚举名称字符串

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ReflexesTest
{
	public class Motion
	{
		public enum POINT
		{
			测试1,
			测试2,
			测试3,
		}

		public Motion(int i, double db, string str)
		{

		}
	}

	public class ConfigFile
	{
		public ConfigFile()
		{

		}
	}

	public class TestClass1
	{
		public enum POINT
		{
			已知类型1,
			已知类型2,
			已知类型3,
		}
		
		public TestClass1()
		{
			int itemp = 8;
			string strtemp = "测试";
			double dbtemp = 8.88;

			//motion类参数:数量、类型、顺序必须完全一致
			object[] objArray = new object[3] { itemp, dbtemp, strtemp };
			
			//同程序集
			string fullName = "ReflexesTest.Motion";//类名称,格式:命名空间.类名
			Type type = Type.GetType(fullName);
			Assembly assembly = Assembly.GetAssembly(type);
			//根据类名称,通过反射获取有参数的类实例
			Motion motion = (Motion)assembly.CreateInstance(fullName, false, BindingFlags.Default, null, objArray, null, null);

			fullName = "ReflexesTest.ConfigFile";//类名称,格式:命名空间.类名
			type = Type.GetType(fullName);
			assembly = Assembly.GetAssembly(type);
			ConfigFile config = (ConfigFile)assembly.CreateInstance(fullName);//根据类名称,通过反射获取无参数的类实例

			//不同程序集;例如:要获取到 MotionIO.dll 内的 Motion_SMC304 类
			//fullName = "MotionIO.Motion_SMC304";//类名称,格式:命名空间.类名
			//string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MotionIO.dll");
			//Assembly assembly = Assembly.LoadFile(path); //绝对路径 加载程序集(EXE 或 DLL) 
			//Motion_SMC304 motion = (Motion)assembly.CreateInstance(fullName, false, BindingFlags.Default, null, objArray, null, null); 

			//获取指定枚举的所有名称字符串
			//未知类型,只有名称字符串
			GetClassEnum("ReflexesTest.Motion");

			//已知类型
			string[] nameList = Enum.GetNames(typeof(POINT));
			string[] nameList1 = Enum.GetNames(typeof(Motion.POINT));
		}

		/// <summary>
		/// 根据类名字符 以反射获取此类内 指定枚举名称中所有名称字符串
		/// </summary>
		/// <param name="className">类名称,格式:命名空间.类名</param>
		public void GetClassEnum(string className)
		{
			//获取调用此方法类名称
			StackTrace trace = new StackTrace();
			StackFrame frame = trace.GetFrame(1);//1代表上级,2代表上上级,以此类推
			string class1 = frame.GetMethod().ReflectedType.FullName;//得到调用此方法类名称;格式:命名空间.类名

			//类名称获取类型
			Type type = Type.GetType(className).GetNestedType("POINT");//获取类下面POINT类型
			List<string> arrayEnum = new List<string>();
			if (type != null)
			{
				string[] nameList = Enum.GetNames(type);//获取POINT枚举内所有枚举名称
				for (int i = 0; i < nameList.Length; i++)
				{
					arrayEnum.Add(nameList[i]);
				}
			}
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值