如何创建泛型类型的类新实例 [英] How do I create new instance of Generic Type Class
问题描述
问题:
- 如何创建,设置,返回和实例类型为T的对象?
- 我将如何访问子类型(标签:数据库)?在静态函数
我想创建一个通用的GetAsClass功能,它会返回一个子类的初始化实例。我无法弄清楚如何创造我想要返回,返回子类类型的类的新实例。
I'm trying to create a generic "GetAsClass" function which would return an initialized instance of the subclass. I can't figure out how to create a new instance of the class I want to return and return the subclass type.
说我有两个类:
- 标签
- 用户
我要创建这将让任何类型它的基类的单一功能。在另一方面,我想,使其静态以及(但我没有获得这个,我不知道如何让子类类型。
I want to create a single function in the base class which will get whatever type it is. On another note, I'd like to make it static as well (but then I don't have access to "this" and I'm not sure how to get the subclass type.
private async Task<T> GetAsClass<T>(string objectId) {
Type classType = this.GetType();
string className = classType.Name;
// This needs to be of type "T" (Tag myTag = new Tag();) How would I accomplish something like this?
object toReturnObject = new object();
ParseObject myParseObject = ParseObject.GetAsParseObject(objectId);
foreach (PropertyInfo field in classType.GetRuntimeProperties()) {
if (field.CanRead) {
string propertyName = StringHelper.ToLowerCamelCase(field.Name);
if (field.PropertyType == typeof(string)) {
string propertyValue = myParseObject.Get<string>(propertyName);
field.SetValue(toReturnObject , propertyValue);
}
if (field.PropertyType == typeof(int)) {
int propertyValue = myParseObject.Get<int>(propertyName);
field.SetValue(toReturnObject, propertyValue);
}
}
}
return toReturnObject;
}
更高的分辨率: http://snag.gy/FbCfu.jpg
Higher Resolution: http://snag.gy/FbCfu.jpg
推荐答案
您可能会发现此页面上的泛型类型约束的是有帮助的。 基本上,你会改变你的类的签名/方法是:
You may find this page on generic type constraints to be helpful. Basically, you would change the signature of your class/method to be:
private async Task<T> GetAsClass<T>(string objectId)
where T: new()
{
...
}
和它将接受类型的T,只有当它提供了一个默认的构造函数不带参数。一旦条件得到保证,那么你的类可以调用新T()
And it will accept types of T only if it provides a default constructor with no arguments. Once that condition is guaranteed, then your class can invoke new T()
这篇关于如何创建泛型类型的类新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!