Programing

C #에서 메서드 내에서 전달 된 제네릭 형식을 인스턴스화하는 방법은 무엇입니까?

lottogame 2020. 9. 9. 20:09
반응형

C #에서 메서드 내에서 전달 된 제네릭 형식을 인스턴스화하는 방법은 무엇입니까?


InstantiateType<T>아래 메서드 내에서 유형 T를 어떻게 인스턴스화 할 수 있습니까?

오류가 발생합니다. 'T'는 '유형 매개 변수'이지만 '변수'처럼 사용됩니다. :

(답변을 보려면 아래로 스크롤)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestGeneric33
{
    class Program
    {
        static void Main(string[] args)
        {
            Container container = new Container();
            Console.WriteLine(container.InstantiateType<Customer>("Jim", "Smith"));
            Console.WriteLine(container.InstantiateType<Employee>("Joe", "Thompson"));
            Console.ReadLine();
        }
    }

    public class Container
    {
        public T InstantiateType<T>(string firstName, string lastName) where T : IPerson
        {
            T obj = T();
            obj.FirstName(firstName);
            obj.LastName(lastName);
            return obj;
        }

    }

    public interface IPerson
    {
        string FirstName { get; set; }
        string LastName { get; set; }
    }

    public class Customer : IPerson
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Company { get; set; }
    }

    public class Employee : IPerson
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int EmployeeNumber { get; set; }
    }
}

답변 :

모든 의견에 감사드립니다. 그들은 저를 올바른 방향으로 이끌었습니다. 이것이 제가하고 싶은 일입니다.

using System;

namespace TestGeneric33
{
    class Program
    {
        static void Main(string[] args)
        {
            Container container = new Container();
            Customer customer1 = container.InstantiateType<Customer>("Jim", "Smith");
            Employee employee1 = container.InstantiateType<Employee>("Joe", "Thompson");
            Console.WriteLine(PersonDisplayer.SimpleDisplay(customer1));
            Console.WriteLine(PersonDisplayer.SimpleDisplay(employee1));
            Console.ReadLine();
        }
    }

    public class Container
    {
        public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
        {
            T obj = new T();
            obj.FirstName = firstName;
            obj.LastName = lastName;
            return obj;
        }
    }

    public interface IPerson
    {
        string FirstName { get; set; }
        string LastName { get; set; }
    }

    public class PersonDisplayer
    {
        private IPerson _person;

        public PersonDisplayer(IPerson person)
        {
            _person = person;
        }

        public string SimpleDisplay()
        {
            return String.Format("{1}, {0}", _person.FirstName, _person.LastName);
        }

        public static string SimpleDisplay(IPerson person)
        {
            PersonDisplayer personDisplayer = new PersonDisplayer(person);
            return personDisplayer.SimpleDisplay();
        }
    }

    public class Customer : IPerson
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Company { get; set; }
    }

    public class Employee : IPerson
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int EmployeeNumber { get; set; }
    }
}

다음과 같이 방법을 선언하십시오.

public string InstantiateType<T>(string firstName, string lastName) 
              where T : IPerson, new()

끝에 추가 제약이 있습니다. 그런 다음 new메서드 본문에 인스턴스를 만듭니다 .

T obj = new T();    

몇 가지 방법.

유형을 지정하지 않으면 생성자가 있어야합니다.

T obj = default(T); //which will produce null for reference types

생성자 사용 :

T obj = new T();

그러나 여기에는 다음 절이 필요합니다.

where T : new()

위의 답변을 확장하려면 where T:new()제네릭 메서드에 제약 조건을 추가 하려면 T에 매개 변수가없는 공용 생성자가 있어야합니다.

If you want to avoid that - and in a factory pattern you sometimes force the others to go through your factory method and not directly through the constructor - then the alternative is to use reflection (Activator.CreateInstance...) and keep the default constructor private. But this comes with a performance penalty, of course.


you want new T(), but you'll also need to add , new() to the where spec for the factory method


A bit old but for others looking for a solution, perhaps this could be of interest: http://daniel.wertheim.se/2011/12/29/c-generic-factory-with-support-for-private-constructors/

Two solutions. One using Activator and one using Compiled Lambdas.

//Person has private ctor
var person = Factory<Person>.Create(p => p.Name = "Daniel");

public static class Factory<T> where T : class 
{
    private static readonly Func<T> FactoryFn;

    static Factory()
    {
        //FactoryFn = CreateUsingActivator();

        FactoryFn = CreateUsingLambdas();
    }

    private static Func<T> CreateUsingActivator()
    {
        var type = typeof(T);

        Func<T> f = () => Activator.CreateInstance(type, true) as T;

        return f;
    }

    private static Func<T> CreateUsingLambdas()
    {
        var type = typeof(T);

        var ctor = type.GetConstructor(
            BindingFlags.Instance | BindingFlags.CreateInstance |
            BindingFlags.NonPublic,
            null, new Type[] { }, null);

        var ctorExpression = Expression.New(ctor);
        return Expression.Lambda<Func<T>>(ctorExpression).Compile();
    }

    public static T Create(Action<T> init)
    {
        var instance = FactoryFn();

        init(instance);

        return instance;
    }
}

Instead of creating a function to Instantiate the type

public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
    {
        T obj = new T();
        obj.FirstName = firstName;
        obj.LastName = lastName;
        return obj;
    }

you could have done it like this

T obj = new T { FirstName = firstName, LastName = lastname };

You can also use reflection to fetch the object's constructor and instantiate that way:

var c = typeof(T).GetConstructor();
T t = (T)c.Invoke();

Using a factory class to build your object with compiled lamba expression: The fastest way I've found to instantiate generic type.

public static class FactoryContructor<T>
{
    private static readonly Func<T> New =
        Expression.Lambda<Func<T>>(Expression.New(typeof (T))).Compile();

    public static T Create()
    {
        return New();
    }
}

Here is the steps I followed to set up the benchmark.

Create my benchmark test method:

static void Benchmark(Action action, int iterationCount, string text)
{
    GC.Collect();
    var sw = new Stopwatch();
    action(); // Execute once before

    sw.Start();
    for (var i = 0; i <= iterationCount; i++)
    {
        action();
    }

    sw.Stop();
    System.Console.WriteLine(text + ", Elapsed: {0}ms", sw.ElapsedMilliseconds);
}

I've also tried using a factory method:

public static T FactoryMethod<T>() where T : new()
{
    return new T();
}

For the tests I've created the simplest class :

public class A { }

The script to test:

const int iterations = 1000000;
Benchmark(() => new A(), iterations, "new A()");
Benchmark(() => FactoryMethod<A>(), iterations, "FactoryMethod<A>()");
Benchmark(() => FactoryClass<A>.Create(), iterations, "FactoryClass<A>.Create()");
Benchmark(() => Activator.CreateInstance<A>(), iterations, "Activator.CreateInstance<A>()");
Benchmark(() => Activator.CreateInstance(typeof (A)), iterations, "Activator.CreateInstance(typeof (A))");

Results over 1 000 000 iterations:

new A(): 11ms

FactoryMethod A(): 275ms

FactoryClass A .Create(): 56ms

Activator.CreateInstance A (): 235ms

Activator.CreateInstance(typeof (A)): 157ms

Remarks: I've tested using both .NET Framework 4.5 and 4.6 (equivalent results).

참고URL : https://stackoverflow.com/questions/658951/in-c-how-to-instantiate-a-passed-generic-type-inside-a-method

반응형