简体   繁体   中英

Is it possible to cast T to a Tuple (with an interface)? "T is ValueTuple<bool, IMyInterface>"

https://dotnetfiddle.net/CZYmsC

using System;

public interface IMyInterface
{
}

public class MyObject : IMyInterface
{
}

public class Program
{
    public static void Main()
    {
        // returns null
        Console.WriteLine(TupleWithInterface((true, new MyObject())));
        
        // returns IMyInterface
        Console.WriteLine(TupleWithClass((true, new MyObject())));
        Console.WriteLine(Interface(new MyObject()));
        Console.WriteLine(Class(new MyObject()));
    }

    public static IMyInterface TupleWithInterface<T>(T gen)
    {
        if (gen is ValueTuple<bool, IMyInterface> a)
        {
            return a.Item2;
        }
        return null;
    }

    public static IMyInterface TupleWithClass<T>(T gen)
    {
        if (gen is ValueTuple<bool, MyObject> b)
        {
            return b.Item2;
        }
        return null;
    }

    public static IMyInterface Interface<T>(T gen)
    {
        if (gen is IMyInterface c)
        {
            return c;
        }
        return null;
    }

    public static IMyInterface Class<T>(T gen)
    {
        if (gen is MyObject d)
        {
            return d;
        }
        return null;
    }
}

In my scenario I need to check to see if T is a tuple<,> that contains IMyInterface and if so extract it. I don't need to worry about anything other than a Tuple of 2. The code above doesn't work the way I was hoping, though really I need to do something even more complicated like this:

if (gen is ValueTuple<object, IMyInterface> || gen is ValueTuple<IMyInterface, object>)

Is something like this even possible? I'm currently handling the scenario where T is IMyInterface with code similar to above but I have no idea how to handle when T is a Tuple.

I would suggest just adding an overload for tuples :

public static IMyInterface TupleWithInterface<T, T1>((T,T1) gen)
{
    if (gen.Item2 is IMyInterface a)
    {
        return a;
    }
    return null;
}

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