gpt4 book ai didi

c# - 在类方法中使用通用列表的字段

转载 作者:行者123 更新时间:2023-12-02 17:58:29 25 4
gpt4 key购买 nike

我有几个通用列表,它们具有不同数量的属性,但它们都有一些
常用字段名称,例如id、port、name等。

我有类似片段的东西。

public bool LookPortName<T>(List<T> list, string id, ref string port, ref string name)  
{
int index;
try
{
//It checks if found id into generic list.
if (index == -1) return false;
//Get portfolio abbreviation.
port = list[index].portfolio.Trim();
//Get portfolio complete name.
name = list[index].portName.Trim();
return true;
}
catch
{
//Other code
}
}

Generic list into method

所有列表都有通用文件,例如“id”、“portfolio”和“portName”,但它们不存在于通用文件中
方法。

是否可以在泛型方法中使用泛型列表的字段?

有人知道如何用清晰的代码示例解决我的问题吗?

非常感谢!

最佳答案

使用接口(interface)

// modify interface to fit your program
interface IPortfolio {
public string Id { get; set; }
public string portfolio { get; set; }
public string portName { get; set; }
}

并将 where T : IPortfolio 添加到方法声明中这允许您像使用 IPortfolio 一样使用 T。

public bool LookPortName<T>(List<T> list, string id, ref string port, ref string name) where T : IPortfolio

然后,让任何需要传递到方法中的类实现接口(interface)

请注意,您不能只使用接口(interface),因为您无法传递列表。

More Info

关于c# - 在类方法中使用通用列表的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75051103/

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