简体   繁体   English

如何创建通用类型类的新实例

[英]How do I create new instance of Generic Type Class

Questions: 问题:

  1. How do I create, set, and return and instantiated object of type "T"? 如何创建,设置和返回类型为“ T”的实例化对象?
  2. How would I access the subclass type (Tag : DataBASE) in a static function? 如何在静态函数中访问子类类型(Tag:DataBASE)?

I'm trying to create a generic "GetAsClass" function which would return an initialized instance of the subclass. 我正在尝试创建一个通用的“ GetAsClass”函数,该函数将返回子类的初始化实例。 I can't figure out how to create a new instance of the class I want to return and return the subclass type. 我不知道如何创建要返回的类的新实例并返回子类类型。

Say I have two classes: 说我有两节课:

  1. Tag 标签
  2. User 用户

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. 另一方面,我也想使其静态化(但是后来我无权访问“ this”,而且我不确定如何获取子类类型。

    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;
    }

到目前为止的代码 Higher Resolution: http://snag.gy/FbCfu.jpg 高分辨率: 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()
{
    ...
}

And it will accept types of T only if it provides a default constructor with no arguments. 并且仅当它提供不带参数的默认构造函数时,它才会接受T的类型。 Once that condition is guaranteed, then your class can invoke new T() 一旦确保该条件,您的类就可以调用new T()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM