是否可以创建没有类型参数的泛型类?

Fil*_*ega 2 c#

据我所知,这是不可能的,但我宁愿问自己并自欺欺人: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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,我只想说操作成功与否,我不需要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);
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

在某些情况下,我只想说操作成功与否,我不需要T值。

在这种情况下,我基本上会遵循Taskand的模型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
}
Run Code Online (Sandbox Code Playgroud)