【问题标题】:Get Full Class Path using Reflection使用反射获取完整的类路径
【发布时间】:2013-07-16 16:52:11
【问题描述】:

我尝试获取给定类名的完整命名空间路径 像这样的例子 输入类名="ABC"

位于 A.B 命名空间中的 ABC 类

我需要像 A.B.ABC 这样的完整路径

我的输入类型传入字符串,如类名而不是类型

Type t= Type.GetType("A.B.ABC");工作

类型 t= Type.GetType("ABC");不工作

如何在 ABC 上找到 A.B.ABC

代码:

 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).ToString() 有什么问题?
  • ABC.cs 是文件名,不是类名。
  • typeof(ABC).FullName 会更明确,并且不依赖于ToString() 的行为。
  • .cs 和这个有什么关系?您的代码在什么上下文中运行,您是在读取 .cs 文件还是文件已编译并且 ABC 类存在于您的程序集中或为您的程序集所知?
  • .cs 是文件名的扩展名

标签: c#


【解决方案1】:

这可以通过

来实现
typeof(ABC).FullName

【讨论】:

    【解决方案2】:
    string fullPathName= typeof(className).AssemblyQualifiedName;
    

    【讨论】:

      【解决方案3】:
      typeof(_Default).UnderlyingSystemType
      

      【讨论】:

        【解决方案4】:

        您可以使用 Linq 扫描您的程序集以查找具有相同名称的类:

        ClassType = Assembly.GetAssembly(typeof(UcDataGridView)).GetTypes().FirstOrDefault(t => t.Name == _ClassFullName);
        

        您必须确定UcDataGridView 在同一个程序集中不会出现多次。

        【讨论】:

        • 一种选择是扫描正在执行的程序集,使用Assembly.GetExecutingAssembly() 检索该程序集。但是,您也可以将引用的程序集搜索为 shown here
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-27
        • 2017-03-16
        • 2014-12-14
        • 2019-08-10
        • 2014-04-02
        • 2016-06-05
        相关资源
        最近更新 更多