问题描述:

I have a generic base to represent some kind of numbers. I need to override some implicit conversions to built-in types (like short, ushort, int, uint, etc...). One possible way is to override every possible type as seen in the code below:

public class MyBaseClass<T>

where T : struct, IComparable, IComparable<T>, IEquatable<T>

{

private T _value;

public MyBaseClass(T value)

{

_value = value;

}

// Implicit Conversions

static public implicit operator MyBaseClass<T>(Int16 value)

=> new MyBaseClass<T>((dynamic)value);

static public implicit operator MyBaseClass<T>(UInt16 value)

=> new MyBaseClass<T>((dynamic)value);

static public implicit operator MyBaseClass<T>(Int32 value)

=> new MyBaseClass<T>((dynamic)value);

// ... some more implicit conversions...

}

The question is: Instead of having to do for every possible option, is there a way to do it only once with something like the below:

static public implicit operator MyBaseClass<T>(U value) where U: struct

=> new MyBaseClass<T>((dynamic)value);

I tried with and without the part where T : struct but with no prevail.

Any idea?

PS: The above code is a .NET Core C# on Mac using Visual Studio Code.

相关阅读:
Top