How can I subtract two generic objects (T - T) in C# (Example: DateTime - DateTime)?

后端 未结 6 1770
再見小時候
再見小時候 2020-12-30 04:42

I wrote a Generic Class:

public class Interval where T : IComparable // for checking that Start < End 
{
    public T Start { ge         


        
6条回答
  •  无人及你
    2020-12-30 05:27

    Try something like this:

    static void Main(string[] args)
    {
        Tuple value = JustAMethod(5, 3);
        if (value.Item2)
        {
            Console.WriteLine(value.Item1);
        }
        else
        {
            Console.WriteLine("Can't substract.");
        }
    }
    public static Tuple JustAMethod(T arg1, T arg2)
    {
        dynamic dArg1 = (dynamic)arg1;
        dynamic dArg2 = (dynamic)arg2;
        dynamic ret;
        try
        {
            ret = dArg1 - dArg2;
            return new Tuple(ret, true);
        }
        catch
        {
            return new Tuple(default(T), false);
        }
    }
    

    How this works: first, you convert the arguments to a dynamic type, and you can easily use operators on the dynamic type. If you wouldn't be able to use the operators, then an exception would be thrown at runtime. So, if you try to substract two objects that you actually can't substract, we'll catch the exception and return false as the second item in the Tuple.

提交回复
热议问题