C#类型的方法重载
发布时间:2020-12-15 06:44:53 所属栏目:百科 来源:网络整理
导读:我想知道以下是否可能.创建接受匿名类型(string,int,decimal,customObject等)的类,然后重载方法根据Type执行不同的操作.例 class TestClassT{ public void GetNamestring() { //do work knowing that the type is a string } public string GetNameint() { /
我想知道以下是否可能.创建接受匿名类型(string,int,decimal,customObject等)的类,然后重载方法根据Type执行不同的操作.例
class TestClass<T> { public void GetName<string>() { //do work knowing that the type is a string } public string GetName<int>() { //do work knowing that the type is an int } public string GetName<int>(int addNumber) { //do work knowing that the type is an int (overloaded) } public string GetName<DateTime>() { //do work knowing that the type is a DateTime } public string GetName<customObject>() { //do work knowing that the type is a customObject type } } 所以现在我可以调用GetName方法,因为我已经在初始化对象时传入了类型,所以找到并执行正确的方法. TestClass foo = new TestClass<int>(); //executes the second method because that's the only one with a "int" type foo.GetName(); 这是可能还是我只是在做梦? 解决方法
你想做的是这样可能的:
class TestClass<T> { public string GetName<T>() { Type typeOfT = typeof(T); if(typeOfT == typeof(string)) { //do string stuff } } } 尽管这是可能的,但是你也是打败仿制药的目的.泛型点是当类型无关紧要时,所以在这种情况下我不认为泛型是适当的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |