[英]Create Instance of Generic Type
I want to build a generic Observable Collection, that load values from the database to its items. 我想构建一个通用的Observable集合,该集合将值从数据库加载到其项中。 In order to assign the values to the property of the item, I want to create an instance of the object.
为了将值分配给项目的属性,我想创建对象的实例。 However, I get an error for the Activator.CreateInstance Command: "'T' is a type, which is not valid in the given context"
但是,我收到了Activator.CreateInstance命令的错误:“'T'是一种类型,在给定的上下文中无效”
public class ListBase<T> : ObservableCollection<T>
{
private DbTable tab;
public ListBase()
{
tab = DbCatalog.Tables.Where(x => x.ModelObjectType == typeof(T).Name).First();
LoadValues();
}
private void LoadValues()
{
foreach (DataRow r in tab.GetValues.Rows)
{
T o = (T)Activator.CreateInstance(T); //<-- The (T) at the end throws the error
var p = o.GetType().GetProperty("xyz_property");
if (p.PropertyType == typeof(int))
{
p.SetValue(o, Convert.ToInt32(r["xyz_fromDB"]));
}
}
}
}
There's no need to use Activator.CreateInstance
, the correct way to do this is to new
it up like you would any object - but this requires a new
constraint : 无需使用
Activator.CreateInstance
,正确的方法是像对任何对象一样对其进行new
-但这需要一个new
约束 :
public class ListBase<T> : ObservableCollection<T> where T : new()
{
}
And now you can simply do this: 现在,您只需执行以下操作:
T o = new T();
You should use: CreateInstance(typeof(T))
, typeof
returns an object of class System.Type
which will work. 您应该使用:
CreateInstance(typeof(T))
, typeof
返回将起作用的System.Type
类的对象。
There is a difference in C# between a 'Generic' type T
and an instance of System.Type
. 在C#中,“通用”类型
T
和System.Type
实例之间存在差异。 Activator.CreateInstance requires the latter. Activator.CreateInstance需要后者。
Edit: You should generally use DavidG's method , it is cleaner. 编辑:通常应该使用DavidG的方法 ,它更干净。 You can use the
Activator
when: 您可以在以下情况下使用
Activator
:
new()
constraint implies a parameterless constructor, with the Activator
you can pass parameters.) new()
约束表示无参数构造函数,使用Activator
可以传递参数。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.