【问题标题】:Accessing attribute via reflection in C#在 C# 中通过反射访问属性
【发布时间】:2013-07-16 03:24:02
【问题描述】:

所以我正在尝试使用反射从 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);
                    }
                }
        }

【问题讨论】:

  • 显示枚举类型的确切代码。我敢打赌,您在 typeof 中引用了错误的 Table 类...
  • 您留下了代码中最重要的部分,即使用 GetCustomAttribute 加载属性的部分。
  • 对于asmTypes 中的每一项,您必须调用GetCustomAttributes
  • 还不清楚“加载表属性”与使用 GetCustomAttribute 相关的含义,它获取应用于实体的属性列表...
  • 在你的属性类Table中,将Name的设置器设为私有,否则在应用属性时可以设置两次,所以使用public string Name { get; private set; }

标签: c# .net reflection .net-4.0 attributes


【解决方案1】:

如果 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

【讨论】:

  • 这给了我 Table 属性,最后,我应该可以从这里开始工作了。谢谢你的帮助。附言这很好用,我希望我能多次+1你的答案。再次感谢。
  • 这不是很安全,.NET 已经有一个 [Table] attribute。所以你的最后一段实际上是不好的建议:)
  • @Hans 它至少可以让他们找到开始识别问题所在的类型,因此我的isSameTypeisSameAssembly 测试;此外,我的“最后一段”是关于称它为TableAttribute(取决于你是否称其为“段落”)-我认为将其命名为TableAttribute 是完全合适的,而且比称它为@要好得多987654332@
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 2021-07-19
相关资源
最近更新 更多