C#小问题,是泛型么?

lovesiyile 2009-10-11 11:20:44
我想写一个方法,参数可以是int,或者double要怎么写
public void fun(type v) {
return "值为"+v;
}
...全文
87 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
lovesiyile 2009-10-11
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 wartim 的回复:]
应该是重载一下函数
[/Quote]
想偷懒才用泛型的
wartim 2009-10-11
  • 打赏
  • 举报
回复
应该是重载一下函数
wartim 2009-10-11
  • 打赏
  • 举报
回复
可以用泛型,但如果是只能输入int或double,多态更适合
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication50
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

int I = 1;
double D = 2;
MessageBox.Show(fun(I));
MessageBox.Show(fun(D));
}

public String fun(int I)
{
return _fun(I);
}

public String fun(double D)
{
return _fun(D);
}

String _fun(Object Obj)
{
return "值为" + Obj.ToString();
}
}
}
a836922329 2009-10-11
  • 打赏
  • 举报
回复
这个 有用
_see_you_again_ 2009-10-11
  • 打赏
  • 举报
回复

public string fun<T>(T v) {
return "值为"+v.ToString();
}
string a=fun<int>(1);
string b=fun<float>(2.3f);


结贴
fflyn 2009-10-11
  • 打赏
  • 举报
回复
呵呵 泛型 最好是容器类
lovexilove 2009-10-11
  • 打赏
  • 举报
回复
不是吧
fflyn 2009-10-11
  • 打赏
  • 举报
回复
也有一个偷懒的方法

public string fun(object v) {
return "值为" + v.toString();
}
SQL77 2009-10-11
  • 打赏
  • 举报
回复
 class Program
{
public class test
{
public void fun<T>(T para)
{
Console.WriteLine(para.ToString());
}
}

static void Main(string[] args)
{
test t = new test();
t.fun<int>(5);
}
}


简单的泛型
lovesiyile 2009-10-11
  • 打赏
  • 举报
回复
我只要一个方法不是要写这么多吧
fflyn 2009-10-11
  • 打赏
  • 举报
回复

// type parameter T in angle brackets
public class GenericList<T>
{
// The nested class is also generic on T.
private class Node
{
// T used in non-generic constructor.
public Node(T t)
{
next = null;
data = t;
}

private Node next;
public Node Next
{
get { return next; }
set { next = value; }
}

// T as private member data type.
private T data;

// T as return type of property.
public T Data
{
get { return data; }
set { data = value; }
}
}

private Node head;

// constructor
public GenericList()
{
head = null;
}

// T as method parameter type:
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}

public IEnumerator<T> GetEnumerator()
{
Node current = head;

while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}

class TestGenericList
{
static void Main()
{
// int is the type argument
GenericList<int> list = new GenericList<int>();

for (int x = 0; x < 10; x++)
{
list.AddHead(x);
}

foreach (int i in list)
{
System.Console.Write(i + " ");
}
System.Console.WriteLine("\nDone");
}
}





仅供参考
fflyn 2009-10-11
  • 打赏
  • 举报
回复
泛型 适合 容器类
呵呵
SQL77 2009-10-11
  • 打赏
  • 举报
回复
用泛型
PUBLIC T GET(T V)
{

}
不太懂,

110,539

社区成员

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

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

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