gpt4 book ai didi

c# - 如何定义类型 T 必须具有字段 "ID"

转载 作者:行者123 更新时间:2023-11-30 13:19:41 27 4
gpt4 key购买 nike

这个例子:

public static void createDictionary<T>(IEnumerable<T> myRecords)
where T: T.ID // Wont Compile
{
IDictionary<int, T> dicionario = myRecords.ToDictionary(r => r.ID);


foreach (var item in dicionario)
{
Console.WriteLine("Key = {0}",item.Key);

Type thisType = item.Value.GetType();

StringBuilder sb = new StringBuilder();

foreach (var itemField in thisType.GetProperties())
{
sb.AppendLine(string.Format("{0} = {1}", itemField.Name, itemField.GetValue(item.Value, null)));
}

Console.WriteLine(sb);
}

}

当参数有一个名为“ID”的字段时,我如何强制传递类型?

最佳答案

你可以创建一个接口(interface):

public interface IWithID
{
// For your method the set(ter) isn't necessary
// public int ID { get; set; }
public int ID { get; }
}

public static void createDictionary<T>(IEnumerable<T> myRecords)
where T: IWithID

您需要以这种方式使用属性,而不是字段。

或者显然您可以使用基类型...

public abstract class WithID
{
// public int ID; // non readonly
public readonly int ID; // can even be a field
}

public static void createDictionary<T>(IEnumerable<T> myRecords)
where T: WithID

另一种解决方案是传递委托(delegate):

public static void createDictionary<T>(IEnumerable<T> myRecords, 
Func<T, int> getID)

然后您使用 GetID 获取 ID,例如 myRecords.ToDictionary(getID)

关于c# - 如何定义类型 T 必须具有字段 "ID",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18356885/

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