【问题标题】:How do you get the type of generic argument from the stackframe?你如何从堆栈帧中获取泛型参数的类型?
【发布时间】:2008-11-15 08:07:09
【问题描述】:

我们应该通过工厂实例化我们的实体,因为它们在客户端和服务器上的设置不同。我想确保是这种情况,但不能让它发挥作用。

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

【问题讨论】:

  • 有趣的问题,但我认为这是不可能的。

标签: c# generics reflection


【解决方案1】:

是否可以在结构上而不是在运行时解决这个问题?您能否将实体和工厂隔离在不同的程序集中,然后为实体构造函数提供internal 范围,以便只有工厂能够调用它们?

【讨论】:

    【解决方案2】:

    问题是工厂方法类型是在运行时解析的,所以该方法被认为是“开放”的。在这种情况下,通用参数类型将返回 TEntity,如您所见。

    不幸的是,(除非我遗漏了什么),获得什么类型的 TEntity 的唯一方法是首先使用 MethodInfo.MakeGenericMethod 创建一个封闭的方法然后执行,这当然不太可能由您的调用者完成.

    有关更多详细信息,请参阅此MSDN page

    【讨论】:

      【解决方案3】:

      感谢您的回复。 将构造函数设置为 internal 是不可能的,因为我们有多个包含实体的程序集。现在我倾向于创建一个类,工厂注册要创建的类型,构造函数检查注册的类型,这不是我想要的解决方案,但现在可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多