如何从堆栈框架中获取通用参数的类型? [英] How do you get the type of generic argument from the stackframe?

查看:80
本文介绍了如何从堆栈框架中获取通用参数的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们应该通过工厂实例化我们的实体,因为它们在客户端和服务器上的设置不同.我想确保是这种情况,但无法完全正常工作.

We are supposed to instantiate our entities through a factory since they are set up differently on the client and server. I want to make sure this is the case but cant quite get it to work.

public interface IEntityFactory
{
    TEntity Create<TEntity>() where TEntity : new();
}

public abstract class Entity
{
    protected Entity()
    {
        VerifyEntityIsCreatedThroughFactory();
    }

    [Conditional("DEBUG")]
    private void VerifyEntityIsCreatedThroughFactory()
    {
        foreach (var methodBase in new StackTrace().GetFrames().Select(x => x.GetMethod()))
        {
            if (!typeof(IEntityFactory).IsAssignableFrom(methodBase.DeclaringType)
                || methodBase.Name != "Create")
                continue;

            // The generic type is TEnitiy but I want the provided type!
            if (methodBase.GetGenericArguments()[0] != GetType())
                Debug.Fail(string.Format("Use factory when creating {0}.", GetType().Name));
        }
    }
}

推荐答案

是否可以从结构上而不是在运行时解决?您可以将实体和工厂隔离在不同的程序集中,然后为实体构造函数指定internal作用域,以便仅工厂可以调用它们吗?

Is possible to address this structurally instead of at runtime? Can you segregate your entities and the factory in a different assembly, then give the entity constructors internal scoping so that only the factory is able to invoke them?

这篇关于如何从堆栈框架中获取通用参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆