您可以使用一个接口:
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);
}
}