开发者

Constraints, generic variables and arithmetic operators [duplicate]

开发者 https://www.devze.com 2022-12-19 20:38 出处:网络
This question already has answers here: Is there a constraint that restricts my generic method to numeric types?
This question already has answers here: Is there a constraint that restricts my generic method to numeric types? (24 answers) Closed 8 years ago.

I’d like to declare a gene开发者_如何学运维ric class Simple where a method called Addition would take two generic variables and add them together using + operator. I thought I could accomplish this by giving class Simple the following constraint:

class Simple<T> where T: int
{
    public T Addition(T firstInt, T secondInt)
    {
        return firstInt + secondInt;
    }
}

I suspect error has something to do with generics only having the following five types of constraints - ClassName, class, struct,InterfaceName, new()? Thus, why don’t generics also support StructureName constraint type? That way we would be able to apply arithmetic operators on generic variables?!

thanx


A StructName constraint wouldn't make sense, since you cannot inherit from value types.

If you had something like class Simple<T> where T : int you could only instantiate Simple<T> with T = int, no type inherits from int or any other value type for that matter.

C# (the CLR) lacks what other languages know as type classes, one popular mechanism to handle operator overloading without hard-coded compiler mechanics (like in C#).


There is no point in constraining a Generic type to a specific struct, since struct types cannot be inherited. This would be identical to writing:

class Simple
{
    public int Addition(int firstInt, int secondInt)
    {
        return firstInt + secondInt;
    }
}

Unfortunately, with support for an IArithmetic interface, generic types with mathematical operations are difficult to support. If you want to see one approach for generic-based mathmetical operators, look to the Generic Operators in MiscUtil.


You constrain T to int. This is no sensible thing to do, as there is only one int type; so you could directly want to write int if you want int.

If you do not constrain T, you cannot use the + operator, since there is no + operator defined on object.

C# generics are not C++ templates.

0

精彩评论

暂无评论...
验证码 换一张
取 消