-1

過去に C++ のコンテキストでこれを質問したことがあると思いますが (私の質問履歴では見つかりません!!)、解決策はテンプレート関数を使用することでした。C++ テンプレートはコンパイル時に解決されるため、機能します。しかし、C# の場合はそうではありません。

public Hashtable ConvertToHashtable<T>(T source) where T has an index operator
{
    Hashtable table = new Hashtable();
    table["apple"] = source["apple"];

    return table;
}

現時点での使用方法の 1 つは、OleDbReader の結果をハッシュテーブルに変換することですが、近いうちにより多くのソース タイプが必要になると予測しています。

4

4 に答える 4

2

次のインターフェイスを使用できます。

public interface IIndexable<T> {
    T this[int index] { get; set; }
    T this[string key] { get; set; }
}

あなたの方法は以下のように表示されます:

public Hashtable ConvertToHashtable<T>(T source) 
    where T : IIndexable<T> {

    Hashtable table = new Hashtable();
    table["apple"] = source["apple"];
    return table;

}

簡単なソースは次のとおりです。

public class Source : IIndexable<Source> {

    public Source this[int index] {
        get {
            // TODO: Implement 
        }
        set {
            // TODO: Implement 
        }
    }

    public Source this[string key] {
        get {
            // TODO: Implement 
        }
        set {
            // TODO: Implement 
        }
    }
}

単純なコンシューマーは次のとおりです。

public class Consumer{

    public void Test(){
        var source = new Source();
        var hashtable = ConvertToHashtable(source);
        // you haven't to write: var hashtable = ConvertToHashtable<Source>(source);
    }

}
于 2011-09-25T07:49:54.110 に答える
1

型パラメータが であることを指定する制約を追加できますIListか?

public Hashtable ConvertToHashtable<T>(T source) where T : IList
{
    Hashtable table = new Hashtable();
    table["apple"] = source["apple"];

    return table;
}

Itemプロパティthis[int index]は演算子ではなく、包含型のプロパティ メンバーです。IListこれを暴露します。

于 2011-09-25T07:49:18.710 に答える
0

C# の演算子にはジェネリック型の制約はありません。これは、C# のジェネリックの制限の 1 つです。

于 2011-09-29T12:43:24.007 に答える
0

実行時チェックが十分であれば、次のように提案されたコメンテーターの 1 つとしてリフレクションを使用できます。

if (typeof (T).GetProperties().Any(property => property.Name.Equals("Item")))
于 2011-09-25T08:00:29.050 に答える