C# 通过C中的反射访问属性#
因此,我尝试使用反射从C#中的自定义属性访问数据,我得到的是: 属性类:C# 通过C中的反射访问属性#,c#,.net,reflection,.net-4.0,attributes,C#,.net,Reflection,.net 4.0,Attributes,因此,我尝试使用反射从C#中的自定义属性访问数据,我得到的是: 属性类: [System.AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly)] public class Table : System.Attribute { public string Name { get; set; } public Table (string name) { this.Name = na
[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();
从这里,我尝试使用汇编方法加载Table属性:getcustomattribute(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
类型),则应该可以使用。然而,这个问题表明出了一些问题。我建议做一些类似的事情:
foreach (var attrib in Attribute.GetCustomAttributes(type))
{
if (attrib.GetType().Name == "Table")
{
Console.WriteLine(attrib.GetType().FullName);
}
}
并在控制台.WriteLine
上放置一个断点,以便查看发生了什么。尤其要注意:
bool isSameType = attrib.GetType() == typeof(Table.Table);
bool isSameAssembly = attrib.GetType().Assembly == typeof(Table.Table).Assembly;
顺便说一句,我强烈建议调用
TableAttribute
显示枚举类型的确切代码。我打赌您在类型的中引用了错误的表类。您留下了代码中最重要的部分,即使用GetCustomAttribute加载属性的部分。在asmTypes
中的每个项上,必须调用GetCustomAttributes
。此外,还不清楚什么是“加载表属性”意味着与使用GetCustomAttribute
获取应用于实体的属性列表相关…在属性类表中,将名称的setter设置为private,因为在应用属性时,它可以设置两次,所以使用公共字符串名称{get;private set;}
。这给了我Table属性,最后,我应该可以从这里开始工作了。谢谢你的帮助。顺便说一句,这真是太好了,我希望我能多次+1你的答案。再次感谢。这不是很安全,.NET已经有一个[表]。因此,您的最后一段实际上是一个糟糕的建议:)@Hans它至少可以让他们找到类型,开始识别问题所在,因此我的isSameType
和IsSameSassembly
测试;此外,我的“最后一段”是关于将其命名为TableAttribute
(取决于您是否将其称为“段落”)——我认为将其命名为TableAttribute
是非常合适的,而且比将其命名为Table
要好得多