【问题标题】:How can I use a custom Attribute within a DynamicProxy Class如何在 DynamicProxy 类中使​​用自定义属性
【发布时间】:2011-04-28 09:40:25
【问题描述】:

我尝试将自定义属性分配给来自动态代理的类

System.Data.Entity.DynamicProxies.Login_A2947F53...

示例类登录

public partial class Login
{
    [CustomAttribute]
    public virtual int Id
    {
        get;
        set;
    }
}

现在我尝试使用泛型和反射访问属性

public static void Process(TSource source)
{
    foreach (PropertyInfo p in target.GetType().GetProperties(flags))
    {
        object[] attr = p.GetCustomAttributes(true); // <- empty
    } 
}

但是没有属性。这是由于 DynmaicProxy 还是我在这里做错了什么?

当我使用没有像这样的动态代理的具体类时,我会得到属性。

public class TestObject
{
    [CustomAttribute]
    public virtual string Name { get; set; }
    [CustomAttribute]
    public virtual string Street { get; set; }
    public virtual int Age { get; set; }
    public virtual string Something { get; set; }
}

【问题讨论】:

    标签: c# entity-framework generics reflection attributes


    【解决方案1】:

    好的,仔细一看这个就很明显了;

    System.Data.Entity.DynamicProxies.Login_A2947F53...
    

    是一个动态代理类型,对任何属性一无所知。所以我必须使用类似的东西:

    foreach (PropertyInfo p in typeof(Login).GetProperties(flags))
    

    而不是动态代理实例来获取类型。最后还有我的属性。

    【讨论】:

      【解决方案2】:

      使用 BaseType

      public static void Process(TSource source)
      {
          foreach (PropertyInfo p in target.GetType().BaseType.GetProperties(flags))
          {
              object[] attr = p.GetCustomAttributes(true);
          } 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-18
        • 2019-05-20
        • 2020-02-13
        • 1970-01-01
        • 2017-09-19
        相关资源
        最近更新 更多