如何在我的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; }
}
}
答案 0 :(得分:103)
声明你的方法:
public string InstantiateType<T>(string firstName, string lastName)
where T : IPerson, new()
注意最后的附加约束。然后在方法体中创建一个new
实例:
T obj = new T();
答案 1 :(得分:27)
几种方式。
不指定类型必须有构造函数:
T obj = default(T); //which will produce null for reference types
使用构造函数:
T obj = new T();
但这需要条款:
where T : new()
答案 2 :(得分:13)
要扩展上述答案,将where T:new()
约束添加到泛型方法将需要T具有公共的无参数构造函数。
如果你想避免这种情况 - 并且在工厂模式中你有时强迫其他人通过你的工厂方法而不是直接通过构造函数 - 那么另一种方法是使用反射(Activator.CreateInstance...
)并保持默认构造函数私有。但当然,这会带来性能损失。
答案 3 :(得分:7)
您想要新 T(),但您还需要将, new()
添加到工厂方法的where
规范中
答案 4 :(得分:4)
有点旧但是对于寻求解决方案的其他人来说,也许这可能是有意义的:http://daniel.wertheim.se/2011/12/29/c-generic-factory-with-support-for-private-constructors/
两种解决方案。一个使用Activator,一个使用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;
}
}
答案 5 :(得分:0)
而不是创建实例化类型的函数
public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
{
T obj = new T();
obj.FirstName = firstName;
obj.LastName = lastName;
return obj;
}
你可以这样做吗
T obj = new T { FirstName = firstName, LastName = lastname };
答案 6 :(得分:0)
您还可以使用反射来获取对象的构造函数并以这种方式实例化:
var c = typeof(T).GetConstructor();
T t = (T)c.Invoke();
答案 7 :(得分:0)
使用工厂类使用已编译的lamba表达式构建对象:我发现实例化泛型类型的最快方法。
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();
}
}
以下是我设置基准测试的步骤。
创建我的基准测试方法:
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);
}
我也尝试过使用工厂方法:
public static T FactoryMethod<T>() where T : new()
{
return new T();
}
对于测试我创建了最简单的类:
public class A { }
要测试的脚本:
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))");
结果超过1 000 000次迭代:
新A():11毫秒
FactoryMethod A():275ms
FactoryClass A .Create():56ms
Activator.CreateInstance A():235ms
Activator.CreateInstance(typeof(A)):157ms
备注:我已使用 .NET Framework 4.5和4.6 (等效结果)进行了测试。