[英]Check if 'this' implements an interface then call its member from inside generic base class for subclass?
I am using Entity Framework in .NET MVC with C#. 我正在使用C#在.NET MVC中使用实体框架。 I've made an interface for POCOs whom I want to track their changes to (custom logic based on POCO, not what EF can already do). 我为要跟踪其更改的POCO创建了一个接口(基于POCO的自定义逻辑,而不是EF可以做到的)。 The interface: 界面:
public interface ITrackChangesService<TClass>
{
void SaveChanges(TClass entity);
}
I am trying to have this be used in my EntitySevice which all POCO services inherit from, the declaration of EntityService: 我试图在所有POCO服务都继承自EntityService的声明的EntitySevice中使用此方法:
public abstract class EntityService<TRepositoryClass, TClass, TDbContext>
where TClass : Entity, new()
where TDbContext : DbContext, new()
where TRepositoryClass : EntityRepository<TClass, TDbContext>, new()
{
As my comments show, I am trying to check if when Save is called from a subclass such as UserService: 如我的评论所示,我试图检查是否从子类(如UserService)调用Save的时间:
public class UserService : EntityService<UserRepository, User, MyDbContext>, ITrackChangesService<User>
To see if the UserService implements ITrackChangesService and if so, call the SaveChanges method on it. 若要查看UserService是否实现ITrackChangesService,如果是,请对其调用SaveChanges方法。 This is being done in my Save method in entity service: 这是通过实体服务中的Save方法完成的:
public virtual void Save(TClass entity)
{
if (entity != null)
{
entity.LastModifiedBy = SessionUtil.UserAbsolute == null ? "System" : SessionUtil.UserAbsolute.NetId;
if (Exists(entity))
{
entity.DateModified = DateTime.Now;
//if(this is ITrackChangesService<TClass>)
//{
// (ITrackChangesService<TClass>) this.SaveChanges(entity);
//}
Repository.Update(entity);
}
else
{
entity.CreatedBy = SessionUtil.UserAbsolute == null ? "System" : SessionUtil.UserAbsolute.NetId;
entity.DateCreated = DateTime.Now;
Repository.Insert(entity);
}
}
}
However I can't seem to be able to call the SaveChanges method off the calling subclass. 但是我似乎无法从调用子类中调用SaveChanges方法。 .SaveChanges
is not recognized. 无法识别.SaveChanges
。 How do I get that to be recognized. 我如何使它得到认可。
You're casting the return value of this.SaveChanges()
instead of this
. 您正在转换this.SaveChanges()
的返回值,而不是this
。
var trackChangesService = this as ITrackChangesService<TClass>;
if(trackChangesService != null)
{
trackChangesService.SaveChanges(entity);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.