c#泛型,懂c#的进来帮忙下,泛型方法写呢?

2025-03-21 04:55:39
推荐回答(5个)
回答1:

楼上说的IList GetAccounts()
并不是泛型方法,只不过是返回值为泛型的普通方法而已。

泛型方法是指类似这样的方法
public class TypeConvertManager
{
public static T Convert(object initialValue, CultureInfo culture)
{
return (T)Convert(initialValue, typeof(T), culture);
}
.....
.....
}
其中方法Convert代表泛型方法,这种方法在调用时需传入方法的具体类型,而这种方法所在的类却不一定是泛型类。

其具体用法与泛型类差不多,在调用时传入具体类型。例如:
TypeConvertUtility.Convert(ddlProvince.SelectedValue)

回答2:

我也是新手.

我说的可能你比较能理解吧.

泛型就是把很多相同的类的实体装到一起去.

List
Dictionary

//T就是实体类的名字.

可以有效减少的拆装箱的操作.

就是在调用泛型中的类的时候可以直接点出方法.属性那些的.

泛型可以作为返回值.

返回一堆的实体类.

引入一个

using System.Collections.Generic;

的命名空间就可以使用反应了.

List Students = new List();

这样就出来一个Students的泛型集合来装所有Student类的实体了.

dictionary

只不过比List泛型多了一个键值对的概念.

恩.

差不多就是这样了吧.

呵呵~~~~

回答3:

public class AccountInfo
{
public AccountInfo ( string userName, string password, string email)
{
this.UserName = userName;
this.Password = password;
this.Email = email;
}
public string UserName
{
get;
set;
}

public string Password
{
get;
set;
}

public string Email
{
get;
set;
}
}

System.Collections.Generic.IList list = new System.Collections.Generic.List ( );

list.Add ( new AccountInfo ( "User Name 1", "Password 1", "Email 1" ) );
list.Add ( new AccountInfo ( "User Name 2", "Password 2", "Email 2" ) );
list.Add ( new AccountInfo ( "User Name 3", "Password 3", "Email 3" ) );

this.grdEmployees.DataSource = dstXML.Tables [ 0 ].DefaultView;// grdEmployees是GridView
this.grdEmployees.DataBind ( );

//补充泛型方法
private System.Collections.Generic.IList GetAccounts()
{
System.Collections.Generic.IList list = new System.Collections.Generic.List ( );

list.Add ( new AccountInfo ( "User Name 1", "Password 1", "Email 1" ) );
list.Add ( new AccountInfo ( "User Name 2", "Password 2", "Email 2" ) );
list.Add ( new AccountInfo ( "User Name 3", "Password 3", "Email 3" ) );

return list;
}

回答4:

泛型类的定义
public class Stacks
{
private List m_data;
public Stacks()
{
m_data = new List();
}

public void Push(T data)
{
this.m_data.Add(data);
}

[QueneException]
public T Pop()
{
T data = this.m_data[this.m_data.Count - 1];
this.m_data.Remove(data);
return data;
}

public bool IsNull
{
get
{
return this.m_data.Count <= 0 ? true : false;
}
}

public void Clear()
{
this.m_data.Clear();
}

public int Length
{
get
{
return this.m_data.Count;
}
}
}

泛型类的使用
Stacks a = new Stacks();
a.Clear();

泛型类在定义时,传递的类型是一个不确定的类型T,在实际使用时,传入已知的确定类型,比如说string等等,那么在定义时所有类型为T的地方将全部替换成你传入的参数类型string等等

回答5:

泛型 你可以当做一个简单的结构(Struct)来学习和使用
我个人的看法是 很多时候你没有必要去看书来做 而是自己心中构想一个小的程序(比如下载器或是日记本) 然后自己慢慢的去写 在克服问题的过程中 你学习的速度也是最快的