gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:08:40 25 4
gpt4 key购买 nike

据我所知,这是不可能的,但我宁愿问并让自己出丑: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);

最佳答案

In some cases, I only want to say that the operation was successful or not, and I don't need the T value.

在这种情况下,我基本上会遵循 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
}

关于c# - 是否可以创建没有类型参数的泛型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68033505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com