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?
You can add, subtract, multiply, and divide double and float variables the same as you can with doubles and ints. The result will again be a double type.
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.
In C# 4, you can use dynamic
if you are confident that float * T => T
.
class Foo<T>
{
public T DoFoo(T bar)
{
dynamic aFloatValue = 1.0f;
// Do other stuff...
return aFloatValue * bar;
}
}
Other options are:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With