在 C# 中的泛型函数中实例化 T 的新对象
Instantiating a new object of T inside of a generic function in C#
我有两个型号都可以使用下面的功能。我创建了一个接口,这两个模型都实现了。
在下面的函数中,我循环遍历传入的列表并使用其中的值创建新版本的列表。
public static IList<T> GenericFunction<T>(IList<T> objList) where T : IProduct
{
// In this function I am doing the following:
IList<T> retVal = new List<T>();
foreach (T obj in objList)
{
T newObj = (T)Activator.CreateInstance(typeof(T));
newObj.Price = obj.BasePrice + obj.OldPrice;
newObj.Description = obj.Name + " " + obj.Description;
retVal.add(newObj);
}
return retVal;
}
以上代码有效,但我有几个问题:
为了使上述功能适用于任何实现 IProduct 的模型,我所做的是我唯一的选择,对吗?起初我想我可以简单地创建一个标准函数,它将 IList<IProduct>
作为参数和 returns IList<IProduct>
。但是后来我 运行 遇到了实例化一个新对象的问题,这导致我创建了一个通用函数。
此外,我可以在 newObj 上使用对象初始值设定项来设置它的属性吗?
看到这个Whosebug post我觉得我应该做一些不同的事情。
如果您知道 IProduct
总是有一个无参数构造函数,您可以通过泛型约束来实现:
public static IList<T> GenericFunction<T>(IList<T> objList) where T : IProduct, new()
{
IList<T> retVal = new List<T>();
foreach (T obj in objList)
{
T newObj = new T();
newObj.Price = obj.BasePrice + obj.OldPrice;
newObj.Description = obj.Name + " " + obj.Description;
retVal.Add(newObj);
}
return retVal;
}
new()
约束 T 使其必须具有无参数构造函数 - 允许它通过 T newObj = new T();
.
实例化
我有两个型号都可以使用下面的功能。我创建了一个接口,这两个模型都实现了。
在下面的函数中,我循环遍历传入的列表并使用其中的值创建新版本的列表。
public static IList<T> GenericFunction<T>(IList<T> objList) where T : IProduct
{
// In this function I am doing the following:
IList<T> retVal = new List<T>();
foreach (T obj in objList)
{
T newObj = (T)Activator.CreateInstance(typeof(T));
newObj.Price = obj.BasePrice + obj.OldPrice;
newObj.Description = obj.Name + " " + obj.Description;
retVal.add(newObj);
}
return retVal;
}
以上代码有效,但我有几个问题:
为了使上述功能适用于任何实现 IProduct 的模型,我所做的是我唯一的选择,对吗?起初我想我可以简单地创建一个标准函数,它将 IList<IProduct>
作为参数和 returns IList<IProduct>
。但是后来我 运行 遇到了实例化一个新对象的问题,这导致我创建了一个通用函数。
此外,我可以在 newObj 上使用对象初始值设定项来设置它的属性吗?
看到这个Whosebug post我觉得我应该做一些不同的事情。
如果您知道 IProduct
总是有一个无参数构造函数,您可以通过泛型约束来实现:
public static IList<T> GenericFunction<T>(IList<T> objList) where T : IProduct, new()
{
IList<T> retVal = new List<T>();
foreach (T obj in objList)
{
T newObj = new T();
newObj.Price = obj.BasePrice + obj.OldPrice;
newObj.Description = obj.Name + " " + obj.Description;
retVal.Add(newObj);
}
return retVal;
}
new()
约束 T 使其必须具有无参数构造函数 - 允许它通过 T newObj = new T();
.