简体   繁体   中英

Accessing attribute via reflection in C#

So I'm trying to access data from a custom attribute in C# using reflection what I have is this:

attribute class:

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

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

I have a separate assembly with the following:

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

In the main program I enumerate all the files in the current directory, and filter all the dll files. Once I have the dll files I run:

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

From here I try and load the Table attribute using the Assembly method: GetCustomAtteribute(Type t, bool inherit)

However the Table attribute doesn't show in any of the dll, nor does it show as any of the types loaded in the assembly.

Any ideas what I'm doing wrong?

Thanks in advance.

UPDATE:

Here is the code that goes over the types and tries to pull the attribute:

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);
                    }
                }
        }

If Table.Table is in a separate assembly that both assemblies reference (ie there is only one Table.Table type), then that should work. However, the issue suggests that something is amiss. I recommend doing something like:

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

and putting a breakpoint on the Console.WriteLine , so you can see what is happening. In particular, look at:

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

Incidentally, I strongly recommend calling that TableAttribute .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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