简体   繁体   English

如何编写将“ +”运算符应用于通用值集合的函数?

[英]How do I write a function that applies the “+” operator to a collection of generic values?

I've got a function that's supposed to add up a bunch of generics, if possible. 如果可能的话,我有一个应该添加一堆泛型的函数。 Otherwise, it returns the value of the last generic it saw. 否则,它返回它看到的最后一个泛型的值。 I'd like to loop through my list of generics, try adding them, and then catch an exception if/when they can't be added. 我想遍历我的泛型列表,尝试添加它们,然后在无法添加时捕获异常。 I understand that you can't try any opperators on a generic, but I can't understand why. 我知道您不能尝试使用任何通用运算符,但我不知道为什么。 Isn't attempting a certain method that may fail exactly why try catch was build for? 难道不是尝试某种可能会失败的方法的原因吗?

I'm pretty sure there isn't an easy way around this, but if there is, let me know. 我很确定这不是一个简单的方法,但是如果有,请告诉我。

Also, the offending code: 另外,令人反感的代码:

T getValueAtTime(float time)
{
    T toReturn = officalValue.Value;

    float maxValue;
    velocities.Sort();
    foreach(ValueAtTime<T> toAdd in velocities)
    {
        if(toAdd.AtTime < time)
        {
            try
            {
                toReturn += toAdd.Value;
            }
            catch(OpperatorUnavailableError err)
            {
                toReturn = toReturn + toAdd.Value;  
            }
            catch(Exception ex)
            {
                toReturn = toAdd.Value; 
            }
        }
    }
    return toReturn;
}

Regardless of c#'s specific prohibition on try-catch in a generic, try catch should not be part of your standard operating method. 不管c#在泛型中对try-catch的具体禁止如何,try catch都不应该成为标准操作方法的一部分。 Your code relies on try-catch in order to overcome an obstacle. 您的代码依靠try-catch来克服障碍。 That is utterly the wrong use of it. 那完全是对它的错误使用。 Try-catch is meant to test operations that might fail for uncontrollable (or at least unpredictable) circumstances, and shut down or retry that operation. Try-catch旨在测试在不可控制(或至少不可预测)的情况下可能失败的操作,并关闭或重试该操作。 It is extremely expensive for managed code to catch the error, and it's not meant to be a logical control mechanism. 托管代码捕获错误的代价非常高,并且并不意味着要成为逻辑控制机制。

Edit I did come up with an alternative, based on your comments explaining your question. 编辑我想出了一个替代方案,根据您的意见,解释你的问题。 You are operating on varying game objects. 您正在对各种游戏对象进行操作。 That doesn't require a generic; 不需要通用的。 it requires an interface. 它需要一个接口。 If all your objects implement the interface IhasValueAtTime with a method float getValueAtTime(float time) , then you can create a function like so float addTwoGetValueAtTimeObjectsSum(IhasValueAtTime item1, IhasValueAtTime item2) 如果所有对象IhasValueAtTime使用float getValueAtTime(float time)方法IhasValueAtTime float getValueAtTime(float time)实现接口IhasValueAtTime ,则可以创建一个类似float addTwoGetValueAtTimeObjectsSum(IhasValueAtTime item1, IhasValueAtTime item2)

I think the problem is that you are expecting different behaviour from toReturn += toAdd.Value and toReturn = toReturn + toAdd.Value . 我认为问题在于您期望与toReturn += toAdd.ValuetoReturn = toReturn + toAdd.Value不同的行为。 They are (almost) exactly the same. 它们(几乎)完全相同。 See this link for further detail. 有关更多详细信息,请参见此链接

So when your try throws an exception, your catch will throw the same exception. 因此,当您尝试抛出异常时,您的捕获将抛出相同的异常。 I think that you would do better to do something like. 我认为您最好做类似的事情。

 T toReturn = officalValue.Value;

float maxValue;
velocities.Sort();
foreach(ValueAtTime<T> toAdd in velocities)
{
    if(toAdd.AtTime < time)
    {
        try
        {
            toReturn += toAdd.Value;
        }
        catch(OpperatorUnavailableError err)
        {
            toReturn = toAdd.Value;
            break; 
        }
    }
}
return toReturn;

I suppose your T is a generic parameter to a class/struct which contains your method. 我想您的T是包含您的方法的类/结构的通用参数。 Now, I don't know what generic constraints you put on T , but is not possible to constrain T to only types which overload the + operator. 现在,我不知道您对T施加了什么通用约束,但是不可能将T约束为仅使+运算符重载的类型。

Therefore, this can not be done if T is a generic parameter. 因此,如果T是通用参数,则无法完成此操作。

What types are you using for T ? 您为T使用什么类型? Simple types like int , double and decimal which have "native" support for + in the language, or user-defined types which overload the + operator? 简单类型(例如intdoubledecimal对语言中的+具有“本机”支持,还是用户定义的类型使+运算符过载?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM