gpt4 book ai didi

c# - 在 C# 中使用跨多种类型的列表

转载 作者:行者123 更新时间:2023-11-30 20:46:02 25 4
gpt4 key购买 nike

<分区>

我正在 C# 应用程序中开发实用程序类。要么我生疏了,要么配置不正确。我想要一个接受任何类型对象列表的类。为了做到这一点,我写了以下内容:

using System;
using System.Collections.Generic;

namespace MyProject
{
public class ItemCollection
{
public List<object> Items { get; set; }

public ItemCollection(List<Object> items)
{
Items.Clear();
foreach (Object item in items)
{
Items.Add(item);
}
}
}
}

然后我调用此代码使用:

var myItem = new MyItem();
var myItems= new List<MyItem>();
myItems.Add(myItem);

var result = new MyCollection(myItems);

这给了我一个编译时错误:

cannot convert from 'System.Collections.Generic.List<MyProject.MyItem>' to 'System.Collections.Generic.List<object>'

我认为一切都源自 object。那么,这不可行吗?

无论哪种方式,我都认为泛型会更合适。我尝试使用以下内容:

public List<T> Items{ get; set; }

然而,这给了我一个编译时错误:

The type or namespace name 'T' could not be found

这对我来说似乎不正确。我做错了什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com