如何编写一个函数来使用索引运算符获取任何对象
我想我过去曾在 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;
}
目前的一种用法是将 OleDbReader 中的结果转换为哈希表,但我预见很快需要更多源类型。
I think I have asked this in the context of C++ (Can't find it in my question history!!) in the past and the solution was to use a template function. As C++ template resolve at compile time, it works. But for C#, it doesn't.
public Hashtable ConvertToHashtable<T>(T source) where T has an index operator
{
Hashtable table = new Hashtable();
table["apple"] = source["apple"];
return table;
}
One usage at the moment is to convert the result in OleDbReader to hashtable, but I am forseeing the need for more source types soon.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用接口:
并且您的方法将如下所示:
一个简单的来源是:
一个简单的消费者是:
You can use an interface:
and your method will be seen as below:
A simple source is:
A simple consumer is:
您可以添加一个约束来指定类型参数是
IList
吗?Item
属性this[int index]
不是运算符,它是包含类型的属性成员。IList
公开了这一点。Could you add a constraint to specify that the type parameter was an
IList
?The
Item
propertythis[int index]
is not an operator, its a property member of the containing type.IList
exposes this.C# 中的运算符没有通用的类型约束 - 它是以下之一C# 中泛型的局限性。
There are no generic type constraints for operators in C# - it is one of the limitations of generics in C#.
如果运行时检查足够好,您可以使用反射作为评论者建议的之一,如下所示:
If runtime checks are good enough, you could use reflection as one of the commentator suggested as follows: