覆盖C#中的类型的静态泛型方法

时间:2014-12-29 23:54:56

标签: c# generics struct static-methods override

我正在尝试编写颜色转换的通用方法(Bgr - > Gray)。我们的想法是进行一些特定类型的转换(例如,对于字节),以及其他类型的回退(默认)转换。 转换方法在Bgr中定义,其中T可以是byte,int,double等。

public struct Bgr<T>
  where T : struct
{
    public T B;
    public T G;
    public T R;

    public unsafe static void Convert(ref Bgr<byte> bgr, ref Gray<byte> gray)
    {
        //should be executed if T is byte...
    }

    public unsafe static void Convert(ref Bgr<T> bgr, ref Gray<T> gray)
    {
        throw new NotSupportedException();
    }
}

转换器类包含“ConvertBgrToGray”方法,该方法调用“Convert”方法。如果TSrcDepth是字节,则调用Bgr的“Convert”的想法,而是调用默认的泛型“Convert”,抛出NotSupportedException。

public static class BgrGrayConverter
{
    public static void ConvertBgrToGray<TSrcDepth, TDstDepth>(Bgr<TSrcDepth>[,] source, Gray<TDstDepth>[,] dest)
        where TSrcDepth: struct
        where TDstDepth: struct
    {
       ...
       Gray<TSrcDepth> dstVal = default(Gray<TSrcDepth>);
       Bgr<TSrcDepth>.Convert(ref source[j, i], ref dstVal);
       ...
    }
}

如何以适当的方式编写它,以便仅在未找到特定类型“覆盖”时才调用默认的Convert方法? (Bgr必须是结构)。

或者如何以“最漂亮的方式”重写它以便有效?

0 个答案:

没有答案