如何初始化泛型类的T类型对象 [英] How to initiate T type object of Generic class

查看:126
本文介绍了如何初始化泛型类的T类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用代理类,它包含T类对象,这也是一个类.我想创建一个T对象.

I have a Generic Proxy Class contains T type object That is also a class. i wants to create a object of T.

class Proxy<T>: IClient
{
    T _classObj;

    public Proxy() 
    {
        this._classObj = //create new instance of type T     
    }
}

推荐答案

如果 T 是一个类,并保证它具有 new()运算符:

If T is a class and it guarantees that it has a new() operator:

class Proxy<T> : IClient where T : class, new() {
    T _classObj;
    public Proxy() {
        this._classObj = new T();
    }
}

否则,或者如果 T struct ,则可以执行以下操作:

otherwise, or if T is a struct, so you can do:

class Proxy<T>: IClient where T : struct {
    T _classObj;
    public Proxy() {
        this._classObj = default(T); // which will be null for reference-types e.g. classes
    }
}

更新:

要在 T 上调用方法,有一些不同的情况.但是,根据问题和评论,我假设 T 是一个 class ,并且它具有一个 new()运算符.此外,它实现了 IGetDataImplementer ,该方法具有名为 GetData 的方法.因此,我们可以:

For call a method on T there is some different situations. But, according to question and comments, I assume that T is a class and it has a new() operator. Also, it implements the IGetDataImplementer which has a method named GetData. So we can:

interface IGetDataImplementer{
    object GetData();
}

class Proxy<T> : IClient where T : class, IGetDataImplementer, new() {
    T _classObj;
    public Proxy() {
        this._classObj = new T();
        var data = this._classObj.GetData();
    }
}

这篇关于如何初始化泛型类的T类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆