如何从堆栈框架中获取generics参数的类型?

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

public interface IEntityFactory { TEntity Create() 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作用域,以便只有工厂能够调用它们吗?

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

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

有关其他详细信息,请参阅此MSDN页面 。

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