我有两种方法,一种是登记内部用户,另一种是登记外部用户。除了对象之外,方法是相同的(参见代码)。我想知道是否有可能有一个接受这两个对象的方法。我想传递一个参数,说明它是内部的还是外部的,并且基于我要调用相应的对象并保存它。不确定是否可能。
public JsonResult CheckInInternal(int ID)
{
var e = EventInternal.Get(ID, EventInternal.FetchType.ID);
if (e.ID == 0)
{
throw new Exception("Registration ID not found.");
}
if (DateTime.Now.Date > e.EventDetail.StartTime.Date)
{
throw new Exception("Check-in has been closed for this class!");
}
e.CheckedIn = true;
e.Save();
return Json(new { success = true, message = "Success!" });
}
public JsonResult CheckInExternal(int ID)
{
var e = EventExternal.Get(ID, EventExternal.FetchType.ID);
if (e.ID == 0)
{
throw new Exception("Registration ID not found.");
}
if (DateTime.Now.Date > e.EventDetail.StartTime.Date)
{
throw new Exception("Check-in has been closed for this class!");
}
e.CheckedIn = true;
e.Save();
return Json(new { success = true, message = "Success!" });
}
答案 0 :(得分:0)
不是说这是最好的方式,但您可以使用Reflection
public enum CallType
{
Internal, External
}
public JsonResult CheckInInternalOrExternal(int ID, CallType type)
{
object e = type == CallType.Internal? EventInternal.Get(ID, EventInternal.FetchType.ID) as object : EventExternal.Get(ID, EventExternal.FetchType.ID) as object;
var idProperty = e.GetType().GetProperty("ID");
var idValue = Convert.ToInt32(IdProperty.GetValue(e));
if (idValue == 0)
{
throw new Exception("Registration ID not found.");
}
if (DateTime.Now.Date > e.EventDetail.StartTime.Date)
{
throw new Exception("Check-in has been closed for this class!");
}
var checkedInProperty = e.GetType().GetProperty("CheckedIn");
checkedInProperty.SetValue(e, true);
var saveMethod = e.GetType().GetMethod("Save");
saveMethod.Invoke(e);
return Json(new { success = true, message = "Success!" });
}
但正如一些评论者所说,Interface
或Generics
是最好的解决方案。视情况而定。