【发布时间】: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