在泛型方法中返回特定类型 [英] Return specific type in generic method

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

问题描述

我编写了以下方法:

public T CreatePackage<T>() where T : new()
{
        var package = new T();

        if (typeof(ComponentInformationPackage) == typeof(T))
        {
            var compInfoPackage = package as ComponentInformationPackage;

            // ...

            return compInfoPackage;
        }

        throw new System.NotImplementedException();
}

我检查 T 是什么类型,并据此处理变量 Package .当我想返回它时,出现编译器错误.

I check what type T is and according to this I treat my variable Package. When I want to return it I get an compiler error.

类型 ComponentInformationPackage 不能隐式转换为T"

"The type ComponentInformationPackage cannot be implicitly converted to T"

我该如何解决这个问题?

How can I solve this problem?

推荐答案

首先:在强制转换无效的情况下,安全的强制转换有效

First: Where a cast doesn't work, a safe cast does work:

return CompInfoPackage as T;

...只要在T上存在class约束:

...provided there's a class constraint on T:

public static T CreatePackage<T>() where T : class, new() { ... }

第二:给出以下代码:

var package = new T();
if (typeof(ComponentInformationPackage) == typeof(T))
{
    var compInfoPackage = package as ComponentInformationPackage;

    // ...

    return (T)compInfoPackage; 
}

...您已经有了对新对象的引用package.由于它的类型为T,因此编译器已经喜欢将其作为返回类型.为什么不退还?

...you already have the reference package to the new object. Since it's of type T, the compiler already likes it as a return type. Why not return that?

var package = new T();
if (typeof(ComponentInformationPackage) == typeof(T))
{
    var compInfoPackage = package as ComponentInformationPackage;

    // ...

    return package; // Same object as compInfoPackage
}

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

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