有没有办法可以使用下面的代码返回Guid?例如,我传递给AddSchedule的是一个类。我想从类中返回一个Id,所以我可以在控制器中使用它。我如何更改代码以解决此问题?
控制器
ModelService.AddSchedule(
new Schedule
{
Id = Guid.Empty,
Start = start,
Stop = end
});
我想用返回Guid做什么
ModelService.AddScheduleToPerson(
new Schedule
{
Id = ?, // get this from above
UserId = userid,
User = username
});
模型
public ObjectCreateStatus AddSchedule(Schedule schedule)
{
var client = new Services.ConfigurationClient();
try
{
ConfigurationMessage cMsg =
client.ConfigService.AddSchedule(
this.ControllerBase.SessionVariables.Credentials,
schedule
);
if (cMsg.Result == ConfigurationResultEnum.Success)
return ObjectCreateStatus.Success;
return ObjectCreateStatus.GeneralError;
}
finally
{
client.Close();
}
}
答案 0 :(得分:1)
如果您要返回GUID以及ObjectCreateStatus,可以考虑使用out参数。
public ObjectCreateStatus AddSchedule(Schedule schedule, out Guid guid) { }
答案 1 :(得分:1)
我创建了一个包装器对象,可以同时包含ObjectCreateStatus
和Guid
并返回该对象。像这样:
public class ObjectCreateResult
{
public ObjectCreateStatus CreateStatus { get; set; }
public Guid CreateGuid { get; set; }
}
public ObjectCreateResult AddSchedule(Schedule schedule)
{
ObjectCreateResult result = new ObjectCreateResult();
var client = new Services.ConfigurationClient();
try
{
ConfigurationMessage cMsg =
client.ConfigService.AddSchedule(
this.ControllerBase.SessionVariables.Credentials,
schedule
);
if (cMsg.Result == ConfigurationResultEnum.Success)
{
result.CreateStatus = ObjectCreateStatus.Success;
result.CreateGuid = Guid.NewGuid(); // Set your actual Guid here
}
else
{
result.CreateStatus = ObjectCreateStatus.GeneralError;
result.CreateGuid = Guid.Empty;
}
}
finally
{
client.Close();
}
return result;
}
答案 2 :(得分:0)
您可以使用out
参数。我在方法的开头分配GUID,但您可能希望根据您的要求更改该逻辑。这是您修改后的代码:
public ObjectCreateStatus AddSchedule(Schedule schedule, out Guid theGuid)
{
theGuid = Guid.NewGuid();
var client = new Services.ConfigurationClient();
try
{
ConfigurationMessage cMsg =
client.ConfigService.AddSchedule(
this.ControllerBase.SessionVariables.Credentials,
schedule
);
if (cMsg.Result == ConfigurationResultEnum.Success)
return ObjectCreateStatus.Success;
return ObjectCreateStatus.GeneralError;
}
finally
{
client.Close();
}
}
答案 3 :(得分:0)
考虑将ObjectCreateStatus
作为一个类:
public class ObjectCreateStatus {
public bool WasSuccessful { get; private set; }
public Guid ScheduleId { get; private set; }
ctor(ConfigurationResultEnum result, Guid guid) {
WasSuccessful = result == ConfigurationResultEnum.Success;
ScheduleId = guid
}
}
public ObjectCreateStatus AddSchedule(Schedule schedule)
{
var client = new Services.ConfigurationClient();
try
{
ConfigurationMessage cMsg =
client.ConfigService.AddSchedule(
this.ControllerBase.SessionVariables.Credentials,
schedule
);
return new ObjectCreateStatus(cMsg.Result, cMsg.Guid(?))
}
finally
{
client.Close();
}
}