c# - 使用反射从元数据类中获取属性属性

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

我有一个名为 Project 的 LINQ 生成类。

我想为生成的属性添加一些属性,所以我定义了一个具有 MetadataType 属性的分部类。

[MetadataType(typeof(Project_HiddenProps))]
public partial class Project : IProject
{
    // There are also a few additional properties defined here.
}

public class Project_HiddenProps
{
    [HiddenColumn]
    public System.Guid Id { get; set; } 
    // Id is an auto-generated property that I've added a custom attribute to
}

后来我用反射尝试获取这个property的属性。

var customAttributes = prop.GetCustomAttributes(false);

不过,我只获得一个 System.Data.Linq.Mapping.ColumnAttribute 类型的属性。我的 HiddenColumn 属性未包含在集合中。我的问题是如何使用反射获取这些元数据属性。

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用约定方法反射(reflect)其他类:

var type = Type.GetType(entityType.FullName + "_HiddenProps," + entityType.AssemblyQualifiedName);
type.GetProperty("Id").GetCustomAttributes(false);

伙伴类不能自动与核心组件合并。这仅用于内部框架元数据(假设这是 MVC,或者可能是动态数据?)

正如@CyanLite 在评论中提到的,您可以使用元数据属性中的 Meta 类 described here (青色添加的链接)。

关于c# - 使用反射从元数据类中获取属性属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7742046/

相关文章:

ASP.NET、IIS 和 COM

java - Java 的 instanceof 和 isInstance() 在 VB 中的等价物是什么?

c# - 将表达式评估为字符串,返回对象?

javascript - 使 asp.net webforms 母版页上的 js 代码中的路径(目录)与根目录中不同级别的页面一起使用

c# - 将列表与文本框一起使用

asp.net - 允许用户更改其帐户页面配色方案的方法

asp.net - 覆盖 ASP.NET WebMethod 参数的 DateTime 序列化

.NET 反射助手 API?

c# - 如何在 C# 中将 mySQL NULL 值转换为整数 0?

c# - TreeView 排序行为 Add 与 AddRange