gpt4 book ai didi

c# - C# 中的泛型构造函数

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:51 24 4
gpt4 key购买 nike

我有以下内容:

GenericClass<T> : Class
{
T Results {get; protected set;}
public GenericClass<T> (T results, Int32 id) : base (id)
{
Results=results;
}
public static GenericClass<T> Something (Int32 id)
{
return new GenericClass<T> (i need to pass something like new T?, id);
}
}

Update T 可以是类型也可以是值,因此使用 new() 对某些类型是可以的,但对值肯定不行。我想这意味着一些类的重新设计。

想法是如何使用构造函数?例如,是否可以传递类似于 new T 的东西(尽管它不应该,因为当时 T 还不知道)或者要避免传递 null 会有什么变化?

最佳答案

这应该有效:

GenericClass<T> : Class where T : new()
{
T Results {get; protected set;}
public GenericClass<T> (T results, Int32 id)
{
Results=results;
}
public GenericClass<T> Something (Int32 id) : this(new T(), id)
{ }
}

关于c# - C# 中的泛型构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4390526/

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