gpt4 book ai didi

c# - 在泛型接口(interface)中实现可空类型

转载 作者:太空狗 更新时间:2023-10-29 17:41:10 24 4
gpt4 key购买 nike

所以在上一个问题中,我询问了关于使用公共(public)类和宾果游戏实现通用接口(interface)的问题,它有效。但是,我希望传入的类型之一是内置的可空类型之一,例如:int、Guid、String 等。

这是我的界面:

public interface IOurTemplate<T, U>
where T : class
where U : class
{
IEnumerable<T> List();
T Get(U id);
}

所以当我这样实现时:

public class TestInterface : IOurTemplate<MyCustomClass, Int32>
{
public IEnumerable<MyCustomClass> List()
{
throw new NotImplementedException();
}

public MyCustomClass Get(Int32 testID)
{
throw new NotImplementedException();
}
}

我收到错误消息:类型“int”必须是引用类型才能将其用作泛型类型或方法“TestApp.IOurTemplate”中的参数“U”

我试图推断类型 Int32?,但同样的错误。有什么想法吗?

最佳答案

我不会真的这样做,但这可能是让它工作的唯一方法。

public class MyWrapperClass<T> where T : struct 
{
public Nullable<T> Item { get; set; }
}

public class MyClass<T> where T : class
{

}

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

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