C#泛型方法是否可以重载,类似于C ++函数重载

时间:2013-10-03 14:50:18

标签: c# generics

C3泛型方法可以重载,类似于C ++函数重载。

以下代码是否正确重载泛型方法

class ReadFile<T> : IDisposable
{

    private FileStream fstream;
    private BinaryReader br;

    public ReadFile(string filename)
    {
       // do all the initialization
    }

    public void readValue(double val)
    {
       val = br.ReadDouble();
    }

    public void readValue(float val)
    {
       val = br.ReadSingle();
    }

    public void readValue(T val)
    {
       throw new Exception("Not implemented");
    }
}

2 个答案:

答案 0 :(得分:3)

您需要模拟readValue方法,而不是模板化类。然后,您可以使用良好的过时重载来实现显式类型。不要忘记将out关键字添加到readValue参数中。快速控制台应用程序演示:

class Program
{
    static void Main(string[] args)
    {
        var rf = new ReadFile();

        double d;
        float f;
        int i;

        Console.WriteLine(string.Format( "{1}: {0}", rf.readValue(out d), d ));
        Console.WriteLine(string.Format( "{1}: {0}", rf.readValue(out f), f ));
        // note you don't have to explicitly specify the type for T
        // it is inferred
        Console.WriteLine(string.Format( "{1}: {0}", rf.readValue(out i), i ));

        Console.ReadLine();
    }
}

public class ReadFile
{
    // overload for double
    public string readValue(out double val)
    {
        val = 1.23;
        return "double";
    }

    // overload for float
    public string readValue(out float val)
    {
        val = 0.12f;
        return "float";
    }

    // 'catch-all' generic method
    public string readValue<T>(out T val)
    {
        val = default(T);
        return string.Format("Generic method called with type {0}", typeof(T));
    }
}

答案 1 :(得分:0)

虽然有些人反对在你描述的事情中使用泛型,但有时候它们是合适的。尽管如此,对于为不同类型执行不同的代码,没有特别方便的模式。可能最好的方法是让您的private static Action<T> readProc = InitReadProc;拥有通用ReadValue(T val)来电readProc(val)InitReadProc方法可能类似于:

ReadFile<float>.readProc = readValue; // Binds to `float` overload
ReadFile<double>.readProc = readValue; // Binds to `double` overload
// etc. for all known overloads
if (readProc == InitReadProc) // The readProc of *this* type (T) didn't get set above
  throw new NotSupportedException(String.Format("Type {0} not available", typeof(T));
else
  readProc();

使用这种方法,第一次尝试为任何类型调用泛型readValue时,它将为所有已知类型填写readProc个委托。将来任何类型调用readValue的尝试都将通过委托调度到适当的方法。请注意,如果需要,可以提供ConfigureReadProc<T>(Action<T> proc)方法,以允许该类的使用者为其他类型设置ReadFile方法。如果需要,还可以使用Reflection来检查类型T是否支持静态readValue(T)方法,如果是,则将委托附加到该方法。