我们应该通过工厂实例化我们的实体,因为它们在客户端和服务器上的设置不同。我想确保情况确实如此,但无法让它正常工作。
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# - 你如何从堆栈框架中获取通用参数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/292295/