将参数传递给模板化类型的C#泛型new()
我试图在添加到列表时通过构造函数创建一个T类型的新对象 我收到一个编译错误:错误消息是: “T”:创建变量实例时无法提供参数 但是我的类确实有一个构造函数参数!我怎样才能做到这一点将参数传递给模板化类型的C#泛型new(),c#,.net,generics,new-operator,C#,.net,Generics,New Operator,我试图在添加到列表时通过构造函数创建一个T类型的新对象 我收到一个编译错误:错误消息是: “T”:创建变量实例时无法提供参数 但是我的类确实有一个构造函数参数!我怎样才能做到这一点 public static string GetAllItems<T>(...) where T : new() { ... List<T> tabListItems = new List<T>(); foreach (ListItem listItem in l
public static string GetAllItems<T>(...) where T : new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T(listItem)); // error here.
}
...
}
公共静态字符串GetAllItems(…),其中T:new()
{
...
List tabListItems=新列表();
foreach(listCollection中的ListItem ListItem)
{
tabListItems.Add(new T(listItem));//此处出错。
}
...
}
您需要添加where T:new(),让编译器知道T保证提供默认构造函数
public static string GetAllItems<T>(...) where T: new()
公共静态字符串GetAllItems(…),其中T:new()
我认为您必须使用where语句约束T,以仅允许具有新构造函数的对象
现在它接受任何东西,包括没有它的对象。为了在函数中创建泛型类型的实例,必须使用“new”标志对其进行约束
公共静态字符串GetAllItems(…),其中T:new()
但是,只有当您想要调用没有参数的构造函数时,这才有效。这里的情况并非如此。相反,您必须提供另一个参数,该参数允许基于参数创建对象。最简单的是函数
public static string GetAllItems<T>(..., Func<ListItem,T> del) {
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(del(listItem));
}
...
}
公共静态字符串GetAllItems(…,Func del){
...
List tabListItems=新列表();
foreach(listCollection中的ListItem ListItem)
{
添加(删除(列表项));
}
...
}
你可以这样称呼它
GetAllItems<Foo>(..., l => new Foo(l));
GetAllItems(…,l=>newfoo(l));
这在您的情况下不起作用。只能指定具有空构造函数的约束:
public static string GetAllItems<T>(...) where T: new()
然后您可以将您的方法更改为:
public static string GetAllItems<T>(...) where T : ITakesAListItem, new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T() { Item = listItem });
}
...
}
public静态字符串GetAllItems(…),其中T:ITakesAListItem,new()
{
...
List tabListItems=新列表();
foreach(listCollection中的ListItem ListItem)
{
Add(新的T(){Item=listItem});
}
...
}
另一种选择是JaredPar描述的
Func
方法。如果您只想使用构造函数参数初始化成员字段或属性,在C#>=3中,您可以非常轻松地执行:
public static string GetAllItems<T>(...) where T : InterfaceOrBaseClass, new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T{ BaseMemberItem = listItem }); // No error, BaseMemberItem owns to InterfaceOrBaseClass.
}
...
}
公共静态字符串GetAllItems(…),其中T:InterfaceOrBaseClass,new()
{
...
List tabListItems=新列表();
foreach(listCollection中的ListItem ListItem)
{
tabListItems.Add(new T{BaseMemberItem=listItem});//无错误,BaseMemberItem拥有InterfaceOrBaseClass。
}
...
}
这和加里·舒特勒说的是同一件事,但我想说一句传统的话
当然,您可以使用属性技巧来做更多的事情,而不仅仅是设置字段值。
属性“set()”可以触发设置其相关字段所需的任何处理以及对象本身的任何其他需要,包括检查是否在使用对象之前进行完全初始化,模拟完整的构造(是的,这是一个丑陋的解决方法,但它克服了M$的新()限制)
我不能确定这是一个计划好的洞还是一个意外的副作用,但它是有效的
非常有趣的是,微软人在语言中添加了新功能,却似乎没有进行全面的副作用分析。
整个通用的东西就是一个很好的证据…因为没有人愿意发布“反思”的答案(我个人认为这是最好的答案),下面是:
public static string GetAllItems<T>(...) where T : new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
Type classType = typeof(T);
ConstructorInfo classConstructor = classType.GetConstructor(new Type[] { listItem.GetType() });
T classInstance = (T)classConstructor.Invoke(new object[] { listItem });
tabListItems.Add(classInstance);
}
...
}
公共静态字符串GetAllItems(…),其中T:new()
{
...
List tabListItems=新列表();
foreach(listCollection中的ListItem ListItem)
{
类型classType=类型(T);
ConstructorInfo classConstructor=classType.GetConstructor(新类型[]{listItem.GetType()});
T classInstance=(T)classConstructor.Invoke(新对象[]{listItem});
tabListItems.Add(classInstance);
}
...
}
编辑:由于.NET 3.5的Activator.CreateInstance,此答案已被弃用,但它在较旧的.NET版本中仍然很有用。这有点脏,当我说“脏”时,我的意思可能是恶心,但假设您可以为参数化类型提供一个空构造函数,那么:
public static T GetTInstance<T>() where T: new()
{
var constructorTypeSignature = new Type[] {typeof (object)};
var constructorParameters = new object[] {"Create a T"};
return (T) new T().GetType().GetConstructor(constructorTypeSignature).Invoke(constructorParameters);
}
publicstatict GetTInstance(),其中T:new()
{
var constructorTypeSignature=新类型[]{typeof(object)};
var constructorParameters=新对象[]{“创建一个T”};
返回(T)新的T().GetType().GetConstructor(constructorTypeSignature).Invoke(constructorParameters);
}
将有效地允许您从带参数的参数化类型构造对象。在这种情况下,我假设我想要的构造函数有一个类型为
object
的参数。我们使用约束允许的空构造函数创建T的一个伪实例,然后使用反射来获取它的一个其他构造函数。在.Net 3.5中,在您可以使用activator类之后:
(T)Activator.CreateInstance(typeof(T), args)
对象初始值设定项 如果带参数的构造函数除了设置属性之外没有做任何事情,那么可以在C#3或更好的版本中使用而不是调用构造函数来完成此操作(正如前面提到的,这是不可能的):
公共静态字符串GetAllItems(…),其中T:new()
{
...
List tabListItems=新列表();
foreach(listCollection中的ListItem ListItem)
{
tabListItems.Add(新的T(){YourPropertyName=listItem});//现在使用对象初始值设定项
}
...
}
使用此方法,也可以将任何构造函数逻辑放入默认(空)构造函数中
Activator.CreateInstance()
或者,您可以这样打电话:
公共静态字符串GetAllItems(…),其中T:new()
{
...
List tabListItems=新列表();
foreach(listCollection中的ListItem ListItem)
{
object[]args=新对象[]{listItem};
tabListItems.Add((T)激活剂
public static T GetTInstance<T>() where T: new()
{
var constructorTypeSignature = new Type[] {typeof (object)};
var constructorParameters = new object[] {"Create a T"};
return (T) new T().GetType().GetConstructor(constructorTypeSignature).Invoke(constructorParameters);
}
(T)Activator.CreateInstance(typeof(T), args)
public static string GetAllItems<T>(...) where T : new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(new T() { YourPropertyName = listItem } ); // Now using object initializer
}
...
}
public static string GetAllItems<T>(...) where T : new()
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
object[] args = new object[] { listItem };
tabListItems.Add((T)Activator.CreateInstance(typeof(T), args)); // Now using Activator.CreateInstance
}
...
}
var x = Activator.CreateInstance(typeof(T), args) as T;
// this delegate is just, so you don't have to pass an object array. _(params)_
public delegate object ConstructorDelegate(params object[] args);
public static ConstructorDelegate CreateConstructor(Type type, params Type[] parameters)
{
// Get the constructor info for these parameters
var constructorInfo = type.GetConstructor(parameters);
// define a object[] parameter
var paramExpr = Expression.Parameter(typeof(Object[]));
// To feed the constructor with the right parameters, we need to generate an array
// of parameters that will be read from the initialize object array argument.
var constructorParameters = parameters.Select((paramType, index) =>
// convert the object[index] to the right constructor parameter type.
Expression.Convert(
// read a value from the object[index]
Expression.ArrayAccess(
paramExpr,
Expression.Constant(index)),
paramType)).ToArray();
// just call the constructor.
var body = Expression.New(constructorInfo, constructorParameters);
var constructor = Expression.Lambda<ConstructorDelegate>(body, paramExpr);
return constructor.Compile();
}
public class MyClass
{
public int TestInt { get; private set; }
public string TestString { get; private set; }
public MyClass(int testInt, string testString)
{
TestInt = testInt;
TestString = testString;
}
}
// you should cache this 'constructor'
var myConstructor = CreateConstructor(typeof(MyClass), typeof(int), typeof(string));
// Call the `myConstructor` function to create a new instance.
var myObject = myConstructor(10, "test message");
var type = typeof(MyClass);
var args = new Type[] { typeof(int), typeof(string) };
// you should cache this 'constructor'
var myConstructor = CreateConstructor(type, args);
// Call the `myConstructor` fucntion to create a new instance.
var myObject = myConstructor(10, "test message");
.Lambda #Lambda1<TestExpressionConstructor.MainWindow+ConstructorDelegate>(System.Object[] $var1) {
.New TestExpressionConstructor.MainWindow+MyClass(
(System.Int32)$var1[0],
(System.String)$var1[1])
}
public object myConstructor(object[] var1)
{
return new MyClass(
(System.Int32)var1[0],
(System.String)var1[1]);
}
private void TestActivator()
{
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 1024 * 1024 * 10; i++)
{
var myObject = Activator.CreateInstance(typeof(MyClass), 10, "test message");
}
sw.Stop();
Trace.WriteLine("Activator: " + sw.Elapsed);
}
private void TestReflection()
{
var constructorInfo = typeof(MyClass).GetConstructor(new[] { typeof(int), typeof(string) });
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 1024 * 1024 * 10; i++)
{
var myObject = constructorInfo.Invoke(new object[] { 10, "test message" });
}
sw.Stop();
Trace.WriteLine("Reflection: " + sw.Elapsed);
}
private void TestExpression()
{
var myConstructor = CreateConstructor(typeof(MyClass), typeof(int), typeof(string));
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 1024 * 1024 * 10; i++)
{
var myObject = myConstructor(10, "test message");
}
sw.Stop();
Trace.WriteLine("Expression: " + sw.Elapsed);
}
TestActivator();
TestReflection();
TestExpression();
Activator: 00:00:13.8210732
Reflection: 00:00:05.2986945
Expression: 00:00:00.6681696
void Main()
{
var values = new Dictionary<string, int> { { "BaseValue", 1 }, { "DerivedValue", 2 } };
Console.WriteLine(CreateObject<Base>(values).ToString());
Console.WriteLine(CreateObject<Derived>(values).ToString());
}
public T CreateObject<T>(IDictionary<string, int> values)
where T : Base, new()
{
var obj = new T();
obj.Initialize(values);
return obj;
}
public class Base
{
public int BaseValue { get; set; }
public virtual void Initialize(IDictionary<string, int> values)
{
BaseValue = values["BaseValue"];
}
public override string ToString()
{
return "BaseValue = " + BaseValue;
}
}
public class Derived : Base
{
public int DerivedValue { get; set; }
public override void Initialize(IDictionary<string, int> values)
{
base.Initialize(values);
DerivedValue = values["DerivedValue"];
}
public override string ToString()
{
return base.ToString() + ", DerivedValue = " + DerivedValue;
}
}
public interface ICreatable1Param
{
void PopulateInstance(object Param);
}
public class MyClass : ICreatable1Param
{
public MyClass() { //do something or nothing }
public void PopulateInstance (object Param)
{
//populate the class here
}
}
public void MyMethod<T>(...) where T : ICreatable1Param, new()
{
//do stuff
T newT = new T();
T.PopulateInstance(Param);
}
public class MyClass : ICreatable1Param
{
public WrappedClass WrappedInstance {get; private set; }
public MyClass() { //do something or nothing }
public void PopulateInstance (object Param)
{
WrappedInstance = new WrappedClass(Param);
}
}
public class T
{
public static implicit operator T(ListItem listItem) => /* ... */;
}
public static string GetAllItems(...)
{
...
List<T> tabListItems = new List<T>();
foreach (ListItem listItem in listCollection)
{
tabListItems.Add(listItem);
}
...
}