c# – 在方法签名中使用泛型有什么好处?
发布时间:2020-12-15 19:58:27 所属栏目:百科 来源:网络整理
导读:(感谢大家的答案,here is my refactored example,反过来关于单一责任原则的另一个StackOverflow问题.) 从PHP到C#,这种语法令人生畏: container.RegisterTypeCustomer("customer1"); 直到我意识到它表达了同样的事情: container.RegisterType(typeof(Custom
(感谢大家的答案,here is my refactored example,反过来关于单一责任原则的另一个StackOverflow问题.)
从PHP到C#,这种语法令人生畏: container.RegisterType<Customer>("customer1"); 直到我意识到它表达了同样的事情: container.RegisterType(typeof(Customer),"customer1"); 正如我在下面的代码中演示的那样. 那么为什么在这里使用泛型(例如整个Unity和大多数C#IoC容器)有一些原因,除了它只是一个更清晰的语法,即你在发送类型时不需要typeof()? using System; namespace TestGenericParameter { class Program { static void Main(string[] args) { Container container = new Container(); container.RegisterType<Customer>("test"); container.RegisterType(typeof(Customer),"test"); Console.ReadLine(); } } public class Container { public void RegisterType<T>(string dummy) { Console.WriteLine("Type={0},dummy={1},name of class={2}",typeof(T),dummy,typeof(T).Name); } public void RegisterType(Type T,string dummy) { Console.WriteLine("Type={0},T,T.Name); } } public class Customer {} } //OUTPUT: //Type=TestGenericParameter.Customer,dummy=test,name of class=Customer //Type=TestGenericParameter.Customer,name of class=Customer 解决方法
主要原因是编译时的类型安全性.如果要传递两个Type对象,则将责任放在开发人员而不是编译器上.
这也是许多IoC容器利用它的原因,因为如果具体类型没有继承抽象类型,编译器会抱怨. public void Register<TAbstract,TConcrete>() where TConcrete : TAbstract { } 此代码仅在TConcrete实现或继承TAbstract时有效.如果此方法采用两个Type参数,则您的方法应验证此关系. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |