我的存储库中有这两个方法:
public IEnumerable<Post> Posts
{
get { return context.Posts; }
}
public IEnumerable<Editables> Editables
{
get { return context.Editables;
}
这是我的方法:
public ActionResult SaveEdit(int activeid,string text, string prop, string REPOMETHOD)
{
var elementToEdit = _repository.<dynamic insert Post or Editable>.ElementAt(activeid);
var type = elementToEdit.GetType();
PropertyInfo p = type.GetProperty(prop);
p.SetValue(elementToEdit, text, null);
_repository.UpdateBigLinkEdit(elementToEdit, activeid);
return null;
}
因此,可以使该方法更加动态并插入正确的方法
_repository.Editables.ElementAt(activeid) OR _repository.Post.ElementAt(activeid);
从我的角度传递网络方法的名称?还是我必须换一种方式?
最佳答案
是的,你可以,通过使用通用方法:
public T GetElement<T>(int id)
{
if (typeof(T) == typeof(Post)) return Posts.ElementAt(id);
if (typeof(T) == typeof(Editable)) return Editables.ElementAt(id);
throw new InvalidTypeException();
}
然后使用它
var element = _repository.GetElement<Post>(activeId);
关于c# - 通过动态选择方法使 Controller 更高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25772732/