C# 使用反射获取完整的类路径
我尝试获取给定类名的完整命名空间路径 榜样 输入类名=ABC 位于a.B命名空间上的类ABC 我需要像ABC一样的完整路径 我的输入类型传入类似类名称的字符串,而不是类型 类型t=Type.GetTypeA.B.ABC;工作 类型t=Type.GetTypeABC;不起作用 如何在ABC上找到A.B.ABC 代码:C# 使用反射获取完整的类路径,c#,C#,我尝试获取给定类名的完整命名空间路径 榜样 输入类名=ABC 位于a.B命名空间上的类ABC 我需要像ABC一样的完整路径 我的输入类型传入类似类名称的字符串,而不是类型 类型t=Type.GetTypeA.B.ABC;工作 类型t=Type.GetTypeABC;不起作用 如何在ABC上找到A.B.ABC 代码: public partial class UcDataGridView : DataGridView { private string _ClassFullName = "
public partial class UcDataGridView : DataGridView
{
private string _ClassFullName = "UcDataGridView";
[Browsable(true), Category("Misc")]
public string ClassFullName
{
get
{ return _ClassFullName; }
set
{
_ClassFullName = value;
if (!string.IsNullOrEmpty(_ClassFullName))
{
ClassType = Type.GetType(_ClassFullName);
if (ClassType != null)
{
if (ClassType.IsClass)
{
PropertyInfo[] props = ClassType.GetProperties();
foreach (var item in props)
{
var txtCol = new DataGridViewTextBoxColumn();
txtCol.Name = "C" + item.Name;
txtCol.HeaderText = item.Name;
txtCol.DataPropertyName = item.Name;
txtCol.ReadOnly = true;
this.Columns.Add(txtCol);
}
}
else
this.Columns.Clear();
}
else
this.Columns.Clear();
}
else
this.Columns.Clear();
Invalidate();
}
}
private Type ClassType { get; set; }
public UcDataGridView()
{
InitializeComponent();
}
}
这可以通过以下方式实现:
typeof(ABC).FullName
您可以使用Linq扫描程序集以查找具有相同名称的类:
ClassType = Assembly.GetAssembly(typeof(UcDataGridView)).GetTypes().FirstOrDefault(t => t.Name == _ClassFullName);
您必须确保UcDataGridView不会在同一程序集中出现多次。typeofABC.ToString有什么问题?ABC.cs是一个文件名,而不是类名。typeofABC.FullName更显式,并且不依赖于ToString的行为。cs与此有什么关系?您的代码在什么上下文中运行,您正在读取.cs文件,还是该文件已编译且ABC类存在于程序集中或为程序集所知?.cs是文件名的扩展名一个选项是扫描正在执行的程序集,该程序集由assembly.GetExecutionGassembly检索。但是,您也可以按以下方式搜索引用的程序集。
typeof(_Default).UnderlyingSystemType
ClassType = Assembly.GetAssembly(typeof(UcDataGridView)).GetTypes().FirstOrDefault(t => t.Name == _ClassFullName);