[英]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;
}
}
在我的场景中,我需要检查 T 是否是包含 IMyInterface 的元组<,> ,如果是则提取它。 除了 2 的元组之外,我不需要担心其他任何事情。上面的代码不能按照我希望的方式工作,尽管我确实需要做一些更复杂的事情,比如:
if (gen is ValueTuple<object, IMyInterface> || gen is ValueTuple<IMyInterface, object>)
这样的事情甚至可能吗? 我目前正在使用与上面类似的代码处理T
是IMyInterface
的场景,但我不知道当T
是元组时如何处理。
我建议只为元组添加重载:
public static IMyInterface TupleWithInterface<T, T1>((T,T1) gen)
{
if (gen.Item2 is IMyInterface a)
{
return a;
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.