(. 감사합니다 답변에 대한 모든 사람, here is my refactored example은 다시 단일 책임 원칙에 대한 또 다른 StackOverflow의 질문)메서드 시그니처에 제네릭을 사용하면 어떤 이점이 있습니까?
C 번호로 PHP에서오고,이 구문은 협박했다 :
container.RegisterType<Customer>("customer1");
나는 실현 될 때까지 다음 코드와 같은 내용을 표현한 것과 같습니다.
container.RegisterType(typeof(Customer), "customer1");
그래서 제네릭이 (예를 들어, 유니티 대부분의 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
매우 유용한 것처럼 들리지만이를 구현하려고하면 "T obj = new T();" 나에게 "new() 제약 조건이 없기 때문에 변수 유형 'T'의 인스턴스를 만들 수 없습니다." 내가 뭘 놓치고 있니? –
내 대답과 같이 제약 조건을 추가해야합니다 :'public T CreateNew() T : new()' –