我为我的方法实现了一个通用的运算结果,它看起来像这样

public class OperResult
{
    public string ErrorCode { get; private set; }
    public string Message { get; private set; }
    public object Data { get; private set; }
    public bool Ok { get; private set; }
    public string IncidentNumber { get; set; }

    public static OperResult Success(Object data = null)
    {
        return new OperResult(data);
    }
}


使用泛型的结果相同

public class OperResult<T>
{
    public string ErrorCode { get; private set; }
    public string Message { get; private set; }
    public T Data { get; private set; }
    public bool Ok { get; private set; }
    public string IncidentNumber { get; private set; }

    public static OperResult<T> Success(T data = null)
    {
        return new OperResult<T>(data);
    }
}


有没有办法组合这两种实现,并同时提供此类的泛型和非泛型版本?



编辑添加有关类型用法的更多信息:

我想轻松创建返回此类型的函数,例如,我希望能够创建以下函数:

OperResult MakeAction()
OperResult<int> GetCount()


如果我使用继承OperResult:OperResult<Object>,则OperResult.Suceess()将产生OperResult<Object>,以下内容将产生编译错误:

OperResult MakeAction(){
  return OperResult.Suceess(); //Cannot convert OperResult<Object> to OperResult
}


GitHub link to OperResult

最佳答案

如评论中已经提到的,非通用名称似乎是OperResult<object>

最初沿这条路线走,但事实证明它不适合所需的用例。
切换到让泛型派生自非泛型并提供新的Data属性。

public class OperResult {

    protected OperResult(object data) {
        this.Data = data;
    }

    public string ErrorCode { get; protected set; }
    public string Message { get; protected set; }
    public object Data { get; protected set; }
    public bool Ok { get; protected set; }
    public string IncidentNumber { get; protected set; }

    public static OperResult Success(object data = null) {
        return new OperResult(data ?? new object());
    }

    public static OperResult<T> Success<T>(T data) {
        return new OperResult<T>(data);
    }
}

public class OperResult<T> : OperResult {

    public OperResult(T data)
        : base(data) {
    }

    public new T Data { get; protected set; }
}


这允许以下语法

int data = 10;
var result = OperResult.Success(data);
//result is OperResult<int>

10-08 19:16