如何从具有泛型返回类型的方法返回一个基元? [英] How can I return a primitive from a method with a generic return type?

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

问题描述

在我的代码中,我有一个通用的getProperty,如下所示:

  public T getProperty< T>( int GUID,字符串属性)
{
PropertyComponent prop;
prop = propDict [GUID];
if(property.Equals(visible))return(T)(Boolean)prop.visible;
if(property.Equals(enabled))return prop.enabled;
if(property.Equals(position))return(T)(Object)prop.position;
}

Visual Studio的编译器给我第3学期没有错误,因为prop.position是一个Vector2。然而,Prop.visible和prop.enabled是bool s,所以当我尝试以这种方式返回它们时,出现无法将类型bool转换为T(以及无法将类型bool转换为T的错误在这种情况下返回bool的正确方法是什么?

解决方案 / div>

您可以将泛型类型参数约束为类或结构(使用where子句),但在您的示例中,您将T类视为类和结构(bool值类型)。

如果您想要返回引用类型对象实例以及值类型数据(如bool),您将不得不将值类型装箱到对象中因为引用类型对象是引用类型和值类型之间唯一的公分母。当您将一个值类型转换为Object时,会自动进行装箱。所以,你所有的返回值应该是类型转换为(T)(object)


In my code I've got a generic, "getProperty" like so:

public T getProperty<T>(int GUID, string property)
{
    PropertyComponent prop;
    prop = propDict[GUID];
    if(property.Equals("visible")) return (T) (Boolean) prop.visible;
    if(property.Equals("enabled")) return prop.enabled;
    if(property.Equals("position")) return (T) (Object) prop.position;
}

Visual Studio's compiler gives me no error for the 3rd term, as prop.position is a Vector2. Prop.visible and prop.enabled, however, are bool s, so when I try to return them in this way, I get an error of "Cannot convert type bool to T" (and "Cannot implicitly convert type bool to T" for the 2nd).

What's the right way to return a bool in this situation?

解决方案

You can constrain a generic type parameter to be a class or a struct (using where clauses) but in your example you're treating the T type as both a class and a struct (the bool value type).

If you want to return reference type object instances as well as value type data (like bool), you're going to have to "box" the value types into objects, as the reference type object is the only common denominator between reference types and value types. Boxing happens automatically when you typecast a value type to Object. So, all your return values should be typecast to (T)(object).

这篇关于如何从具有泛型返回类型的方法返回一个基元?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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