0

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");
    }
}
4

2 に答える 2

3

クラスをテンプレート化する代わりに、readValue メソッドをテンプレート化する必要があります。その後、古き良き時代のオーバーロードを使用して、明示的な型を実装できます。outreadValue パラメータにキーワードを追加することを忘れないでください。クイック コンソール アプリのデモ:

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));
    }
}
于 2013-10-03T15:27:41.273 に答える