基类Generic和继承类.NET

时间:2014-01-30 23:21:25

标签: c# generics

我不知道这是否是正确的标题,如果不是,请为此道歉!

我有一个基类,用于存储异常(如果有的话):

public class BaseException
{
    public bool HasException { get; set; }
    public string ExceptionMessage { get; set; }
}

我还有其他将继承自我的基类的类:

public class BoolValue : BaseException
{
    public bool Value { get; set; }
}

public class LongValue : BaseException
{
    public bool Value { get; set; }
}

因此,当我打电话时,它将是

function LongValue MyFirstFunction()
{
    LongValue data = new LongValue();

    try
    {
        data = ....    
    }
    catch (Exception ex)
    {
        data = BuildException<LongValue>(ex, data);
        return data;
    }
    finally
    {
        data = null;
    }
}

function BoolValue MySecondFunction()
{
    BoolValue data = new BoolValue();
    try
    {
        data = ....
    }
    catch (Exception ex)
    {
        data = BuildException<BoolValue>(ex, data);
        return data;
    }
    finally
    {
        data = null;
    }
}

我想创建Generic函数,我可以在发生错误时设置异常详细信息,但返回原始类类型,即LongValue或LongBool

protected T BuildException<T>(Exception exception, T obj)
{

}

但我确定如何设置HasException和ExceptionMessage,因为即使强制转换它也不起作用,因为编译器告诉我我无法将T转换为BaseException

((BaseException)data).HasException = true;

我希望我的最终功能是这样的:

protected T BuildException<T>(Exception exception, T data)
{
  ((BaseException)data).HasException = true;
  ((BaseException)data).ExceptionMessage = exception.Message;
  return data;
}

我有没有办法实现这个目标,还是应该为我的BaseException创建一个接口?

感谢。

1 个答案:

答案 0 :(得分:8)

在您的方法上设置generic constraint

protected T BuildException<T>(Exception exception, T data) where T : BaseException
{
    data.HasException = true;
    data.ExceptionMessage = exception.Message;
    return data;
}