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]);
}
}
}
}
}
C# 通过类名称字符串获取类实例,枚举名称字符串获取所有枚举名称字符串
最新推荐文章于 2025-03-13 17:00:56 发布