【问题标题】:Accessing member variables in a C# template class [duplicate]访问 C# 模板类中的成员变量 [重复]
【发布时间】: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;
}

【问题讨论】:

  • 你的问题是什么?从我看到你的代码应该可以工作。因为ItemsList&lt;T&gt;,所以元素i 应该是T 类型。我想你需要像where T: Thing 这样的通用约束,假设Thing1Thing2 实现相同的接口。#

标签: c# templates


【解决方案1】:

你需要创建一个包含通用属性的接口,然后让Thing1Thing2 继承它。然后,在GroupOfThings中对你的类型参数&lt;T&gt;添加一个约束,就可以访问该属性了。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 2010-12-08
    • 2020-01-26
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2017-02-19
    相关资源
    最近更新 更多