据我所知,这是不可能的,但我宁愿问自己并出丑:p。
因此,我有一个泛型类Operation<T>
,其中T
是所述运算的返回值。这个类还告诉我一个操作是否成功,如果没有消息(例如异常消息等(
public class Operation<T>
{
public T Value { get; set; }
public bool Succeeded { get; set; }
public string[] Messages { get; set; }
internal Operation(T value)
{
Value = value;
Succeeded = true;
}
internal Operation(bool succeeded, string[] messages = null)
{
Succeeded = succeeded;
Messages = messages;
}
public static Operation<T> Completed(T value)
{
return new Operation<T>(value);
}
public static Operation<T> Success()
{
return new Operation<T>(true);
}
public static Operation<T> Failure(string[] messages)
{
return new Operation<T>(false, messages);
}
}
在某些情况下,我只想说操作是否成功,并且我不需要T
值。
伪代码示例:
// Example operation where I need T value
Operation<int> op = _SumTwoIntegersService.Sum(1, 2);
Console.WriteLine(operation.Value); // 3
// Example operation where I only need the operation status
Operation op = _UserService.Add(user); // Is this possible? Initiate Operation without the type argument
if (op.Succeeded)
return Ok();
else
return BadRequest(op.Messages);
在某些情况下,我只想说操作是否成功,并且我不需要
T
值。
在这种情况下,我基本上遵循Task
和Task<T>
的模型:有一个非泛型基类,它包含不依赖于T
的所有内容,还有一个泛型派生类,它包含T
特定的所有内容:
public class Operation
{
public bool Succeeded { get; set; }
public string[] Messages { get; set; }
// Constructors, other methods
}
public class Operation<T> : Operation
{
public T Value { get; set; }
// Constructors, other methods
}