设置列表= 列表<字符串>; - 有一个脑死亡的时刻字符串>
我确信这很容易。事实上,我确信我之前已经这样做过......
我有一个 MyClass 类,它有 2 个参数 TheString 和 SomeInt
某处,在另一个类中我声明了一个 List
和一个 List
两者具有相同数量的项目。我希望将 MyClassList 中每个 MyClass 中的所有“TheStrings”设置为等于 StringList 中相应的字符串
我设置了 MyClassList = StringList
现在我知道这不起作用,因为它们是不同的类型。我想我必须重载赋值(=)运算符,但我不知道这是如何完成的。我想我总是可以提供一个从 MyClass 调用的方法,但这并不是那么优雅。最优雅的解决方案是什么?
谢谢 托马斯
I'm sure this is easy. Infact I'm sure I've done this before...
I have a class of MyClass which has 2 parameters TheString and SomeInt
Somewhere, in another class I declare an List<MyClass> MyClassList
and a List<String> StringList
Both have the same number of items. I want this to set all "TheStrings" in each MyClass from MyClassList equal to the corresponding String from StringList
I set MyClassList = StringList
Now I know this wont work because they're different types. I think I've got to overload the assignment (=) operator but I can't see how this is done. I suppose I could always provide a method to call from MyClass, but that isn't quite so elegant. What would be the most elegant solution?
Thanks
Thomas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能重载 = 运算符。您可以进行隐式转换,例如来自 MSDN 的示例:
但是对于列表,我认为最好的解决方案是使用 LINQ:
You can't overload the = operator. You could do an implicit conversion, example from MSDN:
However in case of lists I think the best solution is to use LINQ:
信息还远远不够,但是:
我没有对此进行测试,但我想展示我想到的想法。
Nowhere near enough information, but:
I didn't test this, but I wanted to show the idea that came to mind.
当听起来简单的
for
循环就足够了时,您似乎正在寻找优雅,并且很可能是神奇的。您已将问题描述为有两个大小相等的列表,一个是特定类,另一个是字符串。您希望将每个类上的字符串属性设置为相反列表中的相应字符串(因此大概这些已排序并且位于匹配的索引处)。您所需要的只是一个循环。It seems you're looking for elegance and quite possibly magic when it sounds like a simple
for
loop should suffice. You've described the problem as having two equally sized lists, one of a particular class, another of strings. You want to set a string property on each class to the corresponding string in the opposite list (so presumably these are sorted and at matching indexes). All you need is a loop.