简体   繁体   中英

Can you include type parameters when overloading operators in c#?

I want to do something in the same spirit of this non-compiling code

public static B operator + (Func<A,B> f, A a) {
    return f (a);
}

It there a way to specify the types A and B ? I've tried

public static B operator +<A,B> (Func<A,B> f, A a) {
    return f (a);
}

but its too good to be true.

No, operators can't be generic in C#. You can overload operators within generic types, but the operators themselves can't have type parameters.

If you look at the syntax for user-defined operators in the C# spec (eg in section 10.10 of the C# 5 spec) you'll see that it doesn't have anywhere for type parameters (or type parameter constraints) to be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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