gpt4 book ai didi

c# - 在接口(interface)中使用泛型

转载 作者:太空狗 更新时间:2023-10-29 22:13:18 25 4
gpt4 key购买 nike

如何让我的 CookieData 在以下代码中通用?我在 ICookieService2 的声明中遇到编译时错误。

public struct CookieData<T>
{
T Value { get; set; }
DateTime Expires { get; set; }
}

public interface ICookieService2: IDictionary<string, CookieData<T>>
{
// ...
}

我的错误是:

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

我想要 ICookieService2 将通用数据插入其中。谢谢!

编辑 这不会将我锁定在单个 T 中以构建任何 ICookieService2 吗?

编辑 2 我想做的是以下内容:

CookieData<int> intCookie = { Value = 27, Expires = DateTime.Now };
CookieData<string> stringCookie = { Value = "Bob", Expires = DateTime.Now };

CookieService2 cs = new CookieService2();
cs.Add(intCookie);
cs.Add(stringCookie);

最佳答案

看起来你在这里有 3 个选项

使 ICookieService2 通用

public interface ICookieService2<T> : IDictionary<string, CookieData<T> {
...
}

为 CookieData 创建一个非泛型基类并在接口(interface)中使用它

public interface ICookieData {}
public class CookieData<T>: ICookieData{}
public interface ICookieService2 : IDictionary<string, ICookieData> {}

选择一个具体的实现

public interface ICookieService : IDictionary<string, CookieData<int>> {}

关于c# - 在接口(interface)中使用泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/937247/

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