Workaround for C# generic attribute limitation

前端 未结 3 1971
遇见更好的自我
遇见更好的自我 2021-01-07 23:52

As discussed here, C# doesn\'t support generic attribute declaration. So, I\'m not allowed to do something like:

[Audit (UserAction.Update)]
publ         


        
相关标签:
3条回答
  • 2021-01-08 00:11

    You have at least these three possibilities:

    1. You could use reflection to call LoadById
    2. You could create an expression tree that calls LoadById
    3. You could provide a LoadById method in your repository that is not generic.
    0 讨论(0)
  • 2021-01-08 00:13

    You could use reflection to load by id:

    public class AuditAttribute : Attribute
    {
        public AuditAttribute(Type t)
        {
            this.Type = t;
        }
    
        public  Type Type { get; set; }
    
        public void DoSomething()
        {
            //type is not Entity
            if (!typeof(Entity).IsAssignableFrom(Type))
                throw new Exception();
    
            int _id;
    
            IRepository myRepository = new Repository();
            MethodInfo loadByIdMethod =  myRepository.GetType().GetMethod("LoadById");
            MethodInfo methodWithTypeArgument = loadByIdMethod.MakeGenericMethod(this.Type);
            Entity myEntity = (Entity)methodWithTypeArgument.Invoke(myRepository, new object[] { _id });
        }
    }
    
    0 讨论(0)
  • 2021-01-08 00:15

    You could use reflection to invoke the LoadById method. The following msdn article should point you in the right direction:

    http://msdn.microsoft.com/en-us/library/b8ytshk6(v=vs.100).aspx

    0 讨论(0)
提交回复
热议问题