如何使用索引运算符编写函数以获取任何对象 我想我在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; } public Hashtable ConvertToHashtable(T source),其中T有一个索引运算符 { Hashtable=新的Hashtable(); 表[“苹果”]=来源[“苹果”]; 返回表; }
目前的一种用法是将OleDbReader中的结果转换为hashtable,但我认为很快就需要更多的源类型。您是否可以添加一个约束来指定类型参数是一个如何使用索引运算符编写函数以获取任何对象 我想我在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; } public Hashtable ConvertToHashtable(T source),其中T有一个索引运算符 { Hashtable=新的Hashtable(); 表[“苹果”]=来源[“苹果”]; 返回表; },c#,generics,indexer,C#,Generics,Indexer,目前的一种用法是将OleDbReader中的结果转换为hashtable,但我认为很快就需要更多的源类型。您是否可以添加一个约束来指定类型参数是一个IList public Hashtable ConvertToHashtable<T>(T source) where T : IList { Hashtable table = new Hashtable(); table["apple"] = source["apple"]; return table; }
IList
public Hashtable ConvertToHashtable<T>(T source) where T : IList
{
Hashtable table = new Hashtable();
table["apple"] = source["apple"];
return table;
}
public Hashtable ConvertToHashtable(T source),其中T:IList
{
Hashtable=新的Hashtable();
表[“苹果”]=来源[“苹果”];
返回表;
}
项
属性此[int index]
不是运算符,它是包含类型的属性成员<代码>IList公开了这一点。您可以使用一个界面:
public interface IIndexable<T> {
T this[int index] { get; set; }
T this[string key] { get; set; }
}
公共接口IIndexable{
T这个[int索引]{get;set;}
T此[字符串键]{get;set;}
}
您的方法如下所示:
public Hashtable ConvertToHashtable<T>(T source)
where T : IIndexable<T> {
Hashtable table = new Hashtable();
table["apple"] = source["apple"];
return table;
}
公共哈希表ConvertToHashtable(T源)
其中T:IIndexable{
Hashtable=新的Hashtable();
表[“苹果”]=来源[“苹果”];
返回表;
}
一个简单的来源是:
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
}
}
}
公共类源:IIndexable{
公共来源此[int索引]{
得到{
//TODO:实现
}
设置{
//TODO:实现
}
}
公共源此[字符串键]{
得到{
//TODO:实现
}
设置{
//TODO:实现
}
}
}
一个简单的消费者是:
public class Consumer{
public void Test(){
var source = new Source();
var hashtable = ConvertToHashtable(source);
// you haven't to write: var hashtable = ConvertToHashtable<Source>(source);
}
}
公共类消费者{
公开无效测试(){
var source=新源();
var hashtable=ConvertToHashtable(源);
//您不必编写:var hashtable=ConvertToHashtable(source);
}
}
如果运行时检查足够好,您可以按照评论员的建议使用反射,如下所示:
if (typeof (T).GetProperties().Any(property => property.Name.Equals("Item")))
C#中的运算符没有泛型-这是C#中泛型的一个限制。对此,您必须使用反射。C#中的运算符没有泛型类型限制-这是C#中泛型的一个限制。@Oded您能写下您的评论作为答案吗?谢谢。这对于
source[“apple”]
有效的东西来说是没有意义的。