Is there a constraint that restricts my generic method to numeric types?

后端 未结 21 3047
栀梦
栀梦 2020-11-21 05:48

Can anyone tell me if there is a way with generics to limit a generic type argument T to only:

  • Int16
  • Int32
21条回答
  •  耶瑟儿~
    2020-11-21 06:29

    This limitation affected me when I tried to overload operators for generic types; since there was no "INumeric" constraint, and for a bevy of other reasons the good people on stackoverflow are happy to provide, operations cannot be defined on generic types.

    I wanted something like

    public struct Foo
    {
        public T Value{ get; private set; }
    
        public static Foo operator +(Foo LHS, Foo RHS)
        {
            return new Foo { Value = LHS.Value + RHS.Value; };
        }
    }
    

    I have worked around this issue using .net4 dynamic runtime typing.

    public struct Foo
    {
        public T Value { get; private set; }
    
        public static Foo operator +(Foo LHS, Foo RHS)
        {
            return new Foo { Value = LHS.Value + (dynamic)RHS.Value };
        }
    }
    

    The two things about using dynamic are

    1. Performance. All value types get boxed.
    2. Runtime errors. You "beat" the compiler, but lose type safety. If the generic type doesn't have the operator defined, an exception will be thrown during execution.

提交回复
热议问题