c# - 访问 C# 模板类中的成员变量
问题描述
我有几个数据对象类,它们都有一个同名的成员,我想创建一个模板类来保存特定类的列表以及一些附加信息。在此模板的构造函数中,我希望能够遍历列表并在所有项目中设置一个成员。
在 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;
}
解决方案
您需要创建一个包含通用属性的接口,然后拥有Thing1
并Thing2
继承它。<T>
然后,在你的类型参数上添加一个约束GroupOfThings
,你就可以访问该属性了。
public interface IThing
{
string GroupId { get; set; }
}
public class Thing1 : IThing
{
public string Name {get; set;}
public string Id {get; set;}
public string GroupId {get; set;}
}
public class Thing2 : IThing
{
public string Size {get; set;}
public string Id {get; set;}
public string GroupId {get; set;}
}
public class GroupOfThings<T> where T : IThing
{
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)
{
//compiler knows about GroupId from interface
i.GroupId = groupID;
}
}
public List<T> Items;
public string GroupId;
}
推荐阅读
- list - SwiftUI 拖放与列表
- laravel - 减少在 laravel 中打开时间的问题
- java - 使用 selenium webdriver 的多语言自动化测试
- vue.js - Vue 部署到 Heroku,CircleCI 失败:致命:不是 git 存储库(或任何父目录):.git
- python - Python Pandas Multiindexing选择匹配列表中所有值的行
- r - 为数据框中的新列创建嵌套属性
- javascript - 下拉列表问题
- javascript - 错误处理的 PropTypes.func.isRequired 的行为
- r - 如何计算 R 中每列值的频率组合?
- bigcommerce - 从旧网站 Bigcommerce 迁移的客户密码更新