c# - 通过动态选择方法使 Controller 更高效

标签 c# asp.net

我的存储库中有这两个方法:

    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/

相关文章:

c# - ClassName.PropertyName 的正则表达式

c# - : Windows Authentication, 护照认证和表单认证有什么区别?

javascript - 使用JS从Gridview获取值

ASP.net 4.0 母版页页脚 Div

javascript - 我如何将文本框的值放入警报消息框javascript

c# - 如何防止表单多次打开

c# - 使用c#获取本地系统ip地址

c# - Crystal 报表 :Hide/suppress field in report depending on user input/parameter

c# - 根据 "serial"心理模型而不是 "last value"将状态变量赋予任务 lambdas?

ASP.NET DropDownBox 的 Text 和 Value 属性均为 "Text"