C# 2.0 泛型下如何让 new T()调用构造函数时带参?

tfyuan123 2006-02-14 11:55:40
在.NET 2.0 C# 代码如下:
public class note {
private string _value;

public note(string entervalue) {
_value = entervalue;
}
public string getvalue {
get { return _value; }
}
}

public class notes<T> {
string[] items = new string[2];

items[0] = "1";
items[1] = "2";

public T this[int index] {
get {
return new T(index); // <-- 这一步该如何编写?
}
}
}

在public class notes<T> 加入 where T : new() 这个能够调用默认的构造函数
但是无法加入参数的! public class notes<T> where T : new() {...}

求高人解答。
...全文
1002 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
tfyuan123 2006-02-14
  • 打赏
  • 举报
回复
public T this[int index] {
get {
return new T(index); // <-- 这一步该如何编写?
}
}
这步错了 应该是:

public T this[int index] {
get {
return new T(items[index]); // <-- 这一步该如何编写?
}
}
tfyuan123 2006-02-14
  • 打赏
  • 举报
回复
OK ! 非常感谢hdt(倦怠) !

已经解决!
tfyuan123 2006-02-14
  • 打赏
  • 举报
回复
好办法,我试试!
真相重于对错 2006-02-14
  • 打赏
  • 举报
回复
或者使用反射来发现t的代参数的构造函数
public T this[..]
{
get{
Type t = typeof(T);
Type[] tp = new Type[1];
tp[0] = typeof( string );
System.Reflection.ConstructorInfo ci = t.GetConstructor( tp );
object[] op = new object[1];
op[0] = str[nIndex ];
T to = (T)ci.Invoke(op );
return to;
}
}
真相重于对错 2006-02-14
  • 打赏
  • 举报
回复
我没太深入的研究过2.0,不过我感觉这是错误的,因为无法保证T类型一定带有
T( string str )的构造函数
public class notes<T> {
string[] items = new string[2];

items[0] = "1";
items[1] = "2";

public notes<T> this[int index] {
get {
return new notes<T>(index); // <-- 这一步该如何编写?
}
}
public notes(string)
{}
}
tfyuan123 2006-02-14
  • 打赏
  • 举报
回复
顶!

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧