首页 > 解决方案 > 访问 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;
}

标签: c#templates

解决方案


您需要创建一个包含通用属性的接口,然后拥有Thing1Thing2继承它。<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;
}

推荐阅读