【发布时间】:2009-03-19 01:18:25
【问题描述】:
(感谢大家的回答,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}, dummy={1}, name of class={2}", T, dummy, T.Name);
}
}
public class Customer {}
}
//OUTPUT:
//Type=TestGenericParameter.Customer, dummy=test, name of class=Customer
//Type=TestGenericParameter.Customer, dummy=test, name of class=Customer
【问题讨论】: