需要有关泛型方法的帮助 [英] Need help on generic methods

查看:76
本文介绍了需要有关泛型方法的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2种方法,我打算将其重构为单一方法



I have 2 methods which I'm planning to refactor into a single method

IFactory _factory

// Method 1

TClass obj = (TClass )_factory.CreateA(param1);

// Method 2

HClass obj  = (HClass )__factory.CreateB(param2);





现在我想要一个通用方法,它会返回我的通用对象



下面是我试过的代码,但是徒劳无功。获取类型错误





Now I want a generic method which will return me generic object

Below is the code which I tried,But in vain.Get typecast error

T CreateInst<<T>>() 
{
    T _requestType;
        if(_requestType.GetType() == typeof(TClass ))
        {
             _requestType = (TClass)_factory.CreateA(param1)  ;
        }
        else if(_requestType.GetType() == typeof(HClass ))
        {
            _requestType = (HClass)_factory.CreateB(param1)  ;
        }

    return _requestType;
}

推荐答案

这是因为您的方法尝试分配类型的对象TClass HClass T 类型的对象。由于 T 没有约束 T 可以是任何东西,你不能分配 TClass HClass 对任何事情......

That happens because your method tries to assign an object of type TClass or HClass to an object of type T. Since there are no constraints for T, T can be anything and, you cannot assign TClass or HClass to anything...

也许,你打算写下这样的话:

Maybe, you intended to write something like:

T CreateInst<T>(object param1) where T : class
{
    T _requestType = null;

    if(typeof(T) == typeof(TClass))
    {
        _requestType = _factory.CreateA(param1) as T  ;
    }
    else if(typeof(T) == typeof(HClass))
    {
        _requestType = _factory.CreateB(param1) as T ;
    }
 
    return _requestType;
}


T CreateInst<<T>>()
{
    T _requestType;
        if(_requestType is TClass)
        {
             _requestType = (TClass)_factory.CreateA(param1)  ;
        }
        else if(_requestType is HClass )
        {
            _requestType = (HClass)_factory.CreateB(param1)  ;
        }

    return _requestType;
}


这篇关于需要有关泛型方法的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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