Creating a Generic Save() Method for Models

試著忘記壹切 提交于 2019-12-04 11:52:20

Would a generic extension method solve it?

public static T Save<T>(this T current)
{
    var rep = IoCFactory.Current.Container.GetInstance<IRepository<T>>();
    rep.Save(current);
}

You can then constrain it to your ISaveableModel<T> interface. Return type above not implemented, but you can put it to a boolean or status flag, whatever.

In both approaches, the parameter to the Save() function is not of type T. In the first one, it is ISaveableModel<T>, and in the second, it is BaseModel<T>. Since the repository is a generic based on T, Save method will expect a variable of type T. You can add a simple cast to T before you call Save to fix it.

Alternatively, your IRepostory<T> can be changed to

public interface IRepository<T>
{
    T Save(ISaveableModel<T> model);
}

which makes more sense.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!