转换为元组< object,object>. [英] Casting to a Tuple<object,object>
问题描述
考虑一下这段代码,我正在测试一个未知变量,它可能是int,MyObj或Tuple,并且我正在做一些类型检查以查看它是什么,以便我可以继续处理数据视情况而定:
Consider this chunk of code where I'm testing an unknown variable that could be an int, MyObj, or Tuple, and I'm doing some type checking to see what it is so that I can go on and handle the data differently depending on what it is:
class MyObj { }
// ...
void MyMethod(object data) {
if (data is int) Console.Write("Datatype = int");
else if (data is MyObj) Console.Write("Datatype = MyObj");
else if (data is Tuple<object,object>) {
var myTuple = data as Tuple<object,object>;
if (myTuple.Item1 is int && myTuple.Item2 is int) Console.WriteLine("Datatype = Tuple<int,int>");
else if (myTuple.Item1 is int && myTuple.Item2 is MyObj) Console.WriteLine("Datatype = Tuple<int,MyObj>");
// other type checks
}
}
// ...
MyMethod(1); // Works : Datatype = int
MyMethod(new MyObj()); // Works : Datatype = MyObj
MyMethod(Tuple.Create(1, 2)); // Fails
MyMethod(Tuple.Create(1, new MyObj()); // Fails
// and also...
var items = new List<object>() {
1,
new MyObj(),
Tuple.Create(1, 2),
Tuple.Create(1, new MyObj())
};
foreach (var o in items) MyMethod(o);
我的问题是 Tuple< int,MyObj>
不会强制转换为 Tuple< object,object>
,但是我可以单独地强制转换 int
到 object
,而 MyObj
到 object
.
My problem is that a Tuple<int,MyObj>
doesn't cast to Tuple<object,object>
, yet individually, I can cast int
to object
and MyObj
to object
.
我该如何投射?
推荐答案
如果要检查任何对类型,则必须使用反射:
If you want to check for any pair type, you'll have to use reflection:
Type t = data.GetType();
if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Tuple<,>))
{
var types = t.GetGenericArguments();
Console.WriteLine("Datatype = Tuple<{0}, {1}>", types[0].Name, types[1].Name)
}
您也许可以使用重载和动态,而不用手动检查类型:
You may be able to use overloading and dynamic instead of manually inspecting the type:
MyMethod(MyObject obj) { ... }
MyMethod(int i) { ... }
MyMethod(Tuple<int, int> t) { ... }
MyMethod(Tuple<int, MyObject> t) { ... }
foreach(dynamic d in items)
{
MyMethod(d);
}
这将在运行时选择最佳的重载,因此您可以直接访问元组类型.
this will choose the best overload at runtime so you have access the tuple types directly.
这篇关于转换为元组< object,object>.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!