【发布时间】:2020-12-16 14:12:20
【问题描述】:
我有几个数据对象类,它们都有一个同名的成员,我想创建一个模板类来保存特定类的列表以及一些附加信息。在此模板的构造函数中,我希望能够遍历列表并在所有项目中设置一个成员。
在 C++ 中,由于在模板中键入“鸭子”,这将起作用。你会如何在 C# 中做到这一点,(或者你可以)。
例子:
public class Thing1
{
public string Name {get; set;}
public string Id {get; set;}
public string GroupId {get; set;}
}
public class Thing2
{
public string Size {get; set;}
public string Id {get; set;}
public string GroupId {get; set;}
}
public class GroupOfThings<T>
{
public GroupOfThings(List<T> things, string groupID)
{
GroupID = groupID;
Items = things;
// This is the code that I would like to be able to have
// foreach(var i in Items)
// {
// i.GroupId = groupID;
// }
}
public List<T> Items;
public string GroupId;
}
【问题讨论】:
-
你的问题是什么?从我看到你的代码应该可以工作。因为
Items是List<T>,所以元素i应该是T类型。我想你需要像where T: Thing这样的通用约束,假设Thing1和Thing2实现相同的接口。#