繁体   English   中英

通过C#中的反射访问属性

[英]Accessing attribute via reflection in C#

所以我试图使用反射从C#中的自定义属性访问数据我的拥有是这样的:

属性类:

[System.AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)]
public class Table : System.Attribute
{
    public string Name { get; set; }

    public Table (string name)
    {
        this.Name = name;
    }
}

我有一个单独的程序集,包含以下内容:

[Table("Data")]
public class Data
{
    public int PrimaryKey { get; set; }
    public string BankName { get; set; }
    public enum BankType { City, State, Federal };
}

在主程序中,我枚举当前目录中的所有文件,并过滤所有dll文件。 一旦我有了运行的dll文件:

var asm = Assembly.LoadFile(file);
var asmTypes = asm.GetTypes();

从这里我尝试使用Assembly方法加载Table属性: GetCustomAtteribute(Type t, bool inherit)

但是,Table属性不会显示在任何dll中,也不会显示为程序集中加载的任何类型。

我有什么想法我做错了吗?

提前致谢。

更新:

以下是遍历类型并尝试提取属性的代码:

foreach (var dll in dlls)
            {
                var asm = Assembly.LoadFile(dll);
                var asmTypes = asm.GetTypes();
                foreach (var type in asmTypes)
                {
                    Table.Table[] attributes = (Table.Table[])type.GetCustomAttributes(typeof(Table.Table), true);

                    foreach (Table.Table attribute in attributes)
                    {
                        Console.WriteLine(((Table.Table) attribute).Name);
                    }
                }
        }

如果Table.Table位于两个程序集引用的单独程序Table.Table (即只有一个Table.Table类型),那么这应该有效。 然而,这个问题表明有些不对劲。 我推荐做类似的事情:

    foreach (var attrib in Attribute.GetCustomAttributes(type))
    {
        if (attrib.GetType().Name == "Table")
        {
            Console.WriteLine(attrib.GetType().FullName);
        }
    }

并在Console.WriteLine上放置一个断点,这样你就可以看到发生了什么。 特别要看:

bool isSameType = attrib.GetType() == typeof(Table.Table);
bool isSameAssembly = attrib.GetType().Assembly == typeof(Table.Table).Assembly;

顺便说一句,我强烈建议调用TableAttribute

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM