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

Cus*_*dio 15 c# generics reflection

随着讨论这里,C#不支持通用属性的声明.所以,我不允许做类似的事情:

[Audit<User> (UserAction.Update)]
public ActionResult SomeMethod(int id){ ...
Run Code Online (Sandbox Code Playgroud)

这就像我的属性impl类中的魅力一样,因为我需要从通用存储库中调用一个方法:

User fuuObj = (User) repository.LoadById<T>(_id);
Run Code Online (Sandbox Code Playgroud)

我尝试使用解决方案但没有成功.我可以通过类似的东西typeOf(User),但我怎么能用LoadById类型或魔术字符串调用?

*T和User都扩展了一个名为Entity的基类.

Bas*_*Bas 17

您可以使用反射按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 });
    }
}
Run Code Online (Sandbox Code Playgroud)