解决方法为C#通用属性限制

解决方法为C#通用属性限制

本文介绍了解决方法为C#通用属性限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着讨论的,C#不支持通用属性声明。
所以,我不能做这样的事情:

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

[Audit<User> (UserAction.Update)]
public ActionResult SomeMethod(int id){ ...



这将适合喜欢在我的属性实现类魅力,因为我需要调用从一个普通的仓库里的方法:

that would fit like a charm in my attribute impl class, cause I need to call a method from a generic repository:

User fuuObj = (User) repository.LoadById<T>(_id);



我试图用的解决方案。我可以通过类似 typeof运算(用户),但我怎么能叫 LoadById 只是类型或特殊的字符串?

I tried to use this solution without success. I can pass something like typeOf(User), but how can I call LoadById just with type or magic string?

*双方,T和用户,被称为扩展实体的基类。

*Both, T and User, extend a base class called Entity.

推荐答案

您可以使用反射由ID可加载:

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 });
    }
}

这篇关于解决方法为C#通用属性限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:52