這裏的一個問題是,你必須處理多個Tuple
類型:(我假設你想這與元組工作與項目的任意數字)Tuple<T1, T2>
,Tuple<T1, T2, T3>
等
這樣做,看看是否該類型的名稱始於System.Tuple
的有點哈克的方式:
public static IEnumerable TupleToEnumerable(object tuple)
{
Type t = tuple.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition().FullName.StartsWith("System.Tuple"))
{
for (int i = 1;; ++i)
{
var prop = t.GetProperty("Item" + i);
if (prop == null)
yield break;
yield return prop.GetValue(tuple);
}
}
}
如果你不喜歡的FullName.StartsWith(...)
的hackyness你可以把它更加類型安全像這樣:
public static IEnumerable TupleToEnumerable(object tuple)
{
Type t = tuple.GetType();
if (isTupleType(t))
{
for (int i = 1;; ++i)
{
var prop = t.GetProperty("Item" + i);
if (prop == null)
yield break;
yield return prop.GetValue(tuple);
}
}
}
private static bool isTupleType(Type type)
{
if (!type.IsGenericType)
return false;
var def = type.GetGenericTypeDefinition();
for (int i = 2;; ++i)
{
var tupleType = Type.GetType("System.Tuple`" + i);
if (tupleType == null)
return false;
if (def == tupleType)
return true;
}
}
什麼是你發出 –
'VAR值= tuple.GetType()。GetProperties中(),選擇(屬性=> property.GetValue(元組))' – Fabio