我如何乘以一个浮点数和一个泛型类型? [英] How can I multiply a float and a generic type?

查看:124
本文介绍了我如何乘以一个浮点数和一个泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个像下面这样的类:

  class Foo< T> 
{
public T DoFoo(T bar)
{
float aFloatValue = 1.0f;
//做其他的东西...
返回aFloatValue * bar;


当Unity编译这个类时,它给了我这个错误消息:


错误CS0019:运算符 *'不能应用于
float'和`T'

我知道我为T提供的类型将支持与float相乘。如何在这种情况下实现泛乘?

解决方案

Ahhh,好'Haskell。

你不能在C#中做到这一点,你应该有多个DoFoo,一个用于浮点数,一个用于双精度浮点数,另一个用于十进制浮点数。您也可以放弃浮动变体,因为它会隐式地转换为双精度。


I'm programming in Unity 3.4.2 on OS X using C#.

I have a class like the following:

class Foo<T>
{
    public T DoFoo(T bar)
    {
        float aFloatValue = 1.0f;
        // Do other stuff...
        return aFloatValue * bar;
    }
}

When Unity compiles this class, it gives me this error message:

error CS0019: Operator *' cannot be applied to operands of type float' and `T'

I know that the types I provide for T will support multiplication with float. How can I implement generic multiplication in this case?

解决方案

Ahhh, good ol' Haskell.

You can't do that in C#, you should have multiple DoFoo's, one for float, one for double and one for decimal - there aren't all that many float types. You can drop the float variant, too, as it will be implicitly cast into a double anyway.

这篇关于我如何乘以一个浮点数和一个泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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